repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/InstanceOfError.java | package crypto.analysis.errors;
import crypto.analysis.IAnalysisSeed;
import crypto.extractparameter.CallSiteWithExtractedValue;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLRule;
public class InstanceOfError extends ConstraintError {
public InstanceOfError(CallSiteWithExtractedValue cs, CrySLRule rule, IAnalysisSeed objectLocation, ISLConstraint con) {
super(cs, rule, objectLocation, con);
}
@Override
public int hashCode() {
int result = super.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
return true;
}
}
| 716 | 21.40625 | 121 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/NeverTypeOfError.java | package crypto.analysis.errors;
import crypto.analysis.IAnalysisSeed;
import crypto.extractparameter.CallSiteWithExtractedValue;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLRule;
public class NeverTypeOfError extends ConstraintError {
public NeverTypeOfError(CallSiteWithExtractedValue cs, CrySLRule rule, IAnalysisSeed objectLocation, ISLConstraint con) {
super(cs, rule, objectLocation, con);
}
@Override
public int hashCode() {
int result = super.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
return true;
}
}
| 718 | 21.46875 | 122 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/PredicateContradictionError.java | package crypto.analysis.errors;
import java.util.Map.Entry;
import boomerang.jimple.Statement;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLRule;
public class PredicateContradictionError extends AbstractError {
Entry<CrySLPredicate, CrySLPredicate> mismatchedPreds;
public PredicateContradictionError(Statement errorLocation, CrySLRule rule, Entry<CrySLPredicate, CrySLPredicate> disPair) {
super(errorLocation, rule);
mismatchedPreds = disPair;
}
@Override
public void accept(ErrorVisitor visitor) {
visitor.visit(this);
}
@Override
public String toErrorMarkerString() {
return "Predicate mismatch";
}
public Entry<CrySLPredicate, CrySLPredicate> getMismatchedPreds() {
return mismatchedPreds;
}
@Override
public int hashCode() {
int result = super.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
return true;
}
}
| 1,037 | 19.352941 | 125 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/RequiredPredicateError.java | package crypto.analysis.errors;
import boomerang.jimple.Statement;
import crypto.extractparameter.CallSiteWithExtractedValue;
import crypto.reporting.SARIFReporter;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLRule;
/**
* Creates {@link RequiredPredicateError} for all Required Predicate error generates RequiredPredicateError
*
*
* contradictedPredicate a {@link CrySLPredicate} holds the contradicted required predicate or parameter
* extractedValues a {@link CallSiteWithExtractedValue} hold the location value of the missing required predicate or parameter
*/
public class RequiredPredicateError extends AbstractError{
private CrySLPredicate contradictedPredicate;
private CallSiteWithExtractedValue extractedValues;
public RequiredPredicateError(CrySLPredicate contradictedPredicate, Statement location, CrySLRule rule, CallSiteWithExtractedValue multimap) {
super(location, rule);
this.contradictedPredicate = contradictedPredicate;
this.extractedValues = multimap;
}
public CrySLPredicate getContradictedPredicate() {
return contradictedPredicate;
}
public CallSiteWithExtractedValue getExtractedValues() {
return extractedValues;
}
public void accept(ErrorVisitor visitor){
visitor.visit(this);
}
@Override
public String toErrorMarkerString() {
String msg = extractedValues.toString();
msg += " was not properly generated as ";
String predicateName = getContradictedPredicate().getPredName();
String[] parts = predicateName.split("(?=[A-Z])");
msg += parts[0];
for(int i=1; i<parts.length; i++)
msg += parts[i];
if (predicateName.equals("preparedIV") && extractedValues.toString().equals("Third parameter"))
{
msg += " [ with CBC, It's required to use IVParameterSpec]";
}
return msg;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((contradictedPredicate == null) ? 0 : contradictedPredicate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
RequiredPredicateError other = (RequiredPredicateError) obj;
if (contradictedPredicate == null) {
if (other.contradictedPredicate != null)
return false;
} else if (!contradictedPredicate.equals(other.contradictedPredicate))
return false;
return true;
}
}
| 2,454 | 28.22619 | 143 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/TypestateError.java | package crypto.analysis.errors;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import boomerang.jimple.Statement;
import crypto.analysis.IAnalysisSeed;
import crypto.rules.CrySLRule;
import soot.SootMethod;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
public class TypestateError extends ErrorWithObjectAllocation{
private Collection<SootMethod> expectedMethodCalls;
private Set<String> expectedMethodCallsSet = Sets.newHashSet();
public TypestateError(Statement stmt, CrySLRule rule, IAnalysisSeed object, Collection<SootMethod> expectedMethodCalls) {
super(stmt, rule, object);
this.expectedMethodCalls = expectedMethodCalls;
for (SootMethod method : expectedMethodCalls) {
this.expectedMethodCallsSet.add(method.getSignature());
}
}
public Collection<SootMethod> getExpectedMethodCalls() {
return expectedMethodCalls;
}
public void accept(ErrorVisitor visitor){
visitor.visit(this);
}
@Override
public String toErrorMarkerString() {
final StringBuilder msg = new StringBuilder();
boolean useSignatures = useSignatures();
msg.append("Unexpected call to method ");
Statement location = getErrorLocation();
msg.append(getCalledMethodString(location, useSignatures));
msg.append(getObjectType());
final Set<String> altMethods = new HashSet<>();
for (final SootMethod expectedCall : expectedMethodCalls) {
if (useSignatures){
altMethods.add(expectedCall.getSignature().replace("<", "").replace(">", ""));
} else {
altMethods.add(expectedCall.getName().replace("<", "").replace(">", ""));
}
}
if(altMethods.isEmpty()){
msg.append(".");
} else{
msg.append(". Expect a call to one of the following methods ");
msg.append(Joiner.on(",").join(altMethods));
}
return msg.toString();
}
private String getCalledMethodString(Statement location, boolean useSignature) {
Stmt stmt = location.getUnit().get();
if(stmt.containsInvokeExpr()){
if (useSignature){
return stmt.getInvokeExpr().getMethod().getSignature();
} else {
return stmt.getInvokeExpr().getMethod().getName();
}
}
return stmt.toString();
}
/**
* This method checks whether the statement at which the error is located already calls a method with the same name
* as the expected method.
* This occurs when a call to the method with the correct name, but wrong signature is invoked.
*/
private boolean useSignatures(){
Statement errorLocation = getErrorLocation();
if (errorLocation.isCallsite()){
Optional<Stmt> stmtOptional = errorLocation.getUnit();
if (stmtOptional.isPresent()){
Stmt stmt = stmtOptional.get();
if (stmt.containsInvokeExpr()){
InvokeExpr call = stmt.getInvokeExpr();
SootMethod calledMethod = call.getMethod();
for (SootMethod expectedCall : getExpectedMethodCalls()){
if (calledMethod.getName().equals(expectedCall.getName())){
return true;
}
}
}
}
}
return false;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((expectedMethodCallsSet == null) ? 0 : expectedMethodCallsSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
TypestateError other = (TypestateError) obj;
if (expectedMethodCallsSet == null) {
if (other.expectedMethodCallsSet != null)
return false;
} else if (expectedMethodCallsSet != other.expectedMethodCallsSet)
return false;
return true;
}
}
| 3,751 | 28.3125 | 122 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/boomerang/CogniCryptBoomerangOptions.java | package crypto.boomerang;
import com.google.common.base.Optional;
import boomerang.DefaultBoomerangOptions;
import boomerang.callgraph.ObservableICFG;
import boomerang.jimple.AllocVal;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
public class CogniCryptBoomerangOptions extends DefaultBoomerangOptions {
@Override
public Optional<AllocVal> getAllocationVal(SootMethod m, Stmt stmt, Val fact,
ObservableICFG<Unit, SootMethod> icfg) {
if (stmt.containsInvokeExpr()) {
if (stmt instanceof AssignStmt) {
AssignStmt as = (AssignStmt) stmt;
if (as.getLeftOp().equals(fact.value())) {
if(as.getInvokeExpr().getMethod().isNative())
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(as, m)));
}
}
if (stmt.getInvokeExpr().getMethod().isConstructor()
&& (stmt.getInvokeExpr() instanceof InstanceInvokeExpr)) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) stmt.getInvokeExpr();
Value base = iie.getBase();
if (base.equals(fact.value())) {
return Optional.of(new AllocVal(base, m, base, new Statement(stmt, m)));
}
}
}
if (!(stmt instanceof AssignStmt)) {
return Optional.absent();
}
AssignStmt as = (AssignStmt) stmt;
if (!as.getLeftOp().equals(fact.value())) {
return Optional.absent();
}
// if (as.containsInvokeExpr()) {
// for (SootMethod callee : icfg.getCalleesOfCallAt(as)) {
// for (Unit u : icfg.getEndPointsOf(callee)) {
// if (u instanceof ReturnStmt && isAllocationVal(((ReturnStmt) u).getOp())) {
// return Optional.of(
// new AllocVal(as.getLeftOp(), m, ((ReturnStmt) u).getOp(), new Statement((Stmt) u, m)));
// }
// }
// }
// }
if (isAllocationVal(as.getRightOp())) {
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(stmt, m)));
}
return Optional.absent();
}
@Override
public boolean isAllocationVal(Value val) {
if (!trackStrings() && isStringAllocationType(val.getType())) {
return false;
}
if (trackNullAssignments() && val instanceof NullConstant) {
return true;
}
if (arrayFlows() && isArrayAllocationVal(val)) {
return true;
}
if (trackStrings() && val instanceof StringConstant) {
return true;
}
if (!trackAnySubclassOfThrowable() && isThrowableAllocationType(val.getType())) {
return false;
}
return false;
}
@Override
public boolean onTheFlyCallGraph() {
return false;
}
@Override
public boolean arrayFlows() {
return true;
}
@Override
public int analysisTimeoutMS() {
return 5000;
}
@Override
public boolean trackStaticFieldAtEntryPointToClinit() {
return false;
}
}
| 2,893 | 26.046729 | 97 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/boomerang/CogniCryptIntAndStringBoomerangOptions.java | package crypto.boomerang;
import com.google.common.base.Optional;
import boomerang.IntAndStringBoomerangOptions;
import boomerang.callgraph.ObservableICFG;
import boomerang.jimple.AllocVal;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.IntConstant;
import soot.jimple.LengthExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
/**
* Created by johannesspath on 23.12.17.
*/
public class CogniCryptIntAndStringBoomerangOptions extends IntAndStringBoomerangOptions {
@Override
public Optional<AllocVal> getAllocationVal(SootMethod m, Stmt stmt, Val fact,
ObservableICFG<Unit, SootMethod> icfg) {
if (stmt.containsInvokeExpr() && stmt instanceof AssignStmt) {
AssignStmt as = (AssignStmt) stmt;
if (as.getLeftOp().equals(fact.value())) {
SootMethod method = as.getInvokeExpr().getMethod();
String sig = method.getSignature();
if (sig.equals("<java.math.BigInteger: java.math.BigInteger valueOf(long)>")) {
Value arg = as.getInvokeExpr().getArg(0);
return Optional.of(new AllocVal(as.getLeftOp(), m, arg, new Statement(stmt, m)));
}
if(sig.equals("<java.lang.String: char[] toCharArray()>")) {
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(stmt, m)));
}
if(sig.equals("<java.lang.String: byte[] getBytes()>")) {
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(stmt, m)));
}
if(as.getInvokeExpr().getMethod().isNative())
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(as, m)));
if(Scene.v().isExcluded(as.getInvokeExpr().getMethod().getDeclaringClass()))
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(as, m)));
if(!Scene.v().getCallGraph().edgesOutOf(stmt).hasNext()) {
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(as, m)));
}
}
}
if (stmt.containsInvokeExpr()) {
if (stmt.getInvokeExpr().getMethod().isConstructor()
&& (stmt.getInvokeExpr() instanceof InstanceInvokeExpr)) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) stmt.getInvokeExpr();
Value base = iie.getBase();
if (base.equals(fact.value())) {
return Optional.of(new AllocVal(base, m, base, new Statement(stmt, m)));
}
}
}
if (!(stmt instanceof AssignStmt)) {
return Optional.absent();
}
AssignStmt as = (AssignStmt) stmt;
if (!as.getLeftOp().equals(fact.value())) {
return Optional.absent();
}
if (as.getRightOp() instanceof StaticFieldRef) {
StaticFieldRef sfr = (StaticFieldRef) as.getRightOp();
if(sfr.getField().toString().equals("<java.security.spec.RSAKeyGenParameterSpec: java.math.BigInteger F4>")) {
return Optional.of(new AllocVal(as.getLeftOp(), m, IntConstant.v(65537), new Statement(stmt, m)));
}
if(sfr.getField().toString().equals("<java.security.spec.RSAKeyGenParameterSpec: java.math.BigInteger F0>")) {
return Optional.of(new AllocVal(as.getLeftOp(), m, IntConstant.v(3), new Statement(stmt, m)));
}
}
if (as.getRightOp() instanceof LengthExpr) {
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(stmt, m)));
}
// if (as.containsInvokeExpr()) {
// for (SootMethod callee : icfg.getCalleesOfCallAt(as)) {
// for (Unit u : icfg.getEndPointsOf(callee)) {
// if (u instanceof ReturnStmt && isAllocationVal(((ReturnStmt) u).getOp())) {
// return Optional.of(
// new AllocVal(as.getLeftOp(), m, ((ReturnStmt) u).getOp(), new Statement((Stmt) u, m)));
// }
// }
// }
// }
if (isAllocationVal(as.getRightOp())) {
return Optional.of(new AllocVal(as.getLeftOp(), m, as.getRightOp(), new Statement(stmt, m)));
}
return Optional.absent();
}
@Override
public boolean onTheFlyCallGraph() {
return false;
}
@Override
public boolean arrayFlows() {
return true;
}
@Override
public int analysisTimeoutMS() {
return 5000;
}
@Override
public boolean trackStaticFieldAtEntryPointToClinit() {
return false;
}
}
| 4,242 | 33.778689 | 113 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/constraints/ConstraintSolver.java | package crypto.constraints;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import boomerang.jimple.Statement;
import crypto.analysis.AlternativeReqPredicate;
import crypto.analysis.AnalysisSeedWithSpecification;
import crypto.analysis.ClassSpecification;
import crypto.analysis.CrySLResultsReporter;
import crypto.analysis.RequiredCrySLPredicate;
import crypto.analysis.errors.AbstractError;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.ForbiddenMethodError;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.ImpreciseValueExtractionError;
import crypto.analysis.errors.InstanceOfError;
import crypto.analysis.errors.NeverTypeOfError;
import crypto.extractparameter.CallSiteWithExtractedValue;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.extractparameter.ExtractedValue;
import crypto.interfaces.ICrySLPredicateParameter;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLArithmeticConstraint;
import crypto.rules.CrySLComparisonConstraint;
import crypto.rules.CrySLConstraint;
import crypto.rules.CrySLConstraint.LogOps;
import crypto.rules.CrySLMethod;
import crypto.rules.CrySLObject;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLSplitter;
import crypto.rules.CrySLValueConstraint;
import crypto.typestate.CrySLMethodToSootMethod;
import soot.Body;
import soot.IntType;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Constant;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.LongConstant;
import soot.jimple.NewExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.internal.JNewArrayExpr;
public class ConstraintSolver {
private static final Logger LOGGER = LoggerFactory.getLogger(ConstraintSolver.class);
private final List<ISLConstraint> allConstraints;
private final Set<ISLConstraint> relConstraints = Sets.newHashSet();
private final List<ISLConstraint> requiredPredicates = Lists.newArrayList();
private final Collection<Statement> collectedCalls;
private final Multimap<CallSiteWithParamIndex, ExtractedValue> parsAndVals;
public final static List<String> predefinedPreds = Arrays.asList("callTo", "noCallTo", "neverTypeOf", "length", "notHardCoded", "instanceOf");
private final CrySLResultsReporter reporter;
private final AnalysisSeedWithSpecification object;
private final ClassSpecification classSpec;
private Collection<CallSiteWithParamIndex> parameterAnalysisQuerySites;
private Multimap<CallSiteWithParamIndex, Type> propagatedTypes;
public ConstraintSolver(AnalysisSeedWithSpecification object, Collection<Statement> collectedCalls, CrySLResultsReporter crySLResultsReporter) {
this.object = object;
this.classSpec = object.getSpec();
this.parsAndVals = object.getParameterAnalysis().getCollectedValues();
this.propagatedTypes = object.getParameterAnalysis().getPropagatedTypes();
this.parameterAnalysisQuerySites = object.getParameterAnalysis().getAllQuerySites();
this.collectedCalls = collectedCalls;
this.allConstraints = this.classSpec.getRule().getConstraints();
for (ISLConstraint cons : allConstraints) {
Set<String> involvedVarNames = cons.getInvolvedVarNames();
for (CallSiteWithParamIndex cwpi : this.parameterAnalysisQuerySites) {
involvedVarNames.remove(cwpi.getVarName());
}
if (involvedVarNames.isEmpty() || (cons.toString().contains("speccedKey") && involvedVarNames.size() == 1)) {
if (cons instanceof CrySLPredicate) {
RequiredCrySLPredicate pred = retrieveValuesForPred(cons);
if (pred != null) {
CrySLPredicate innerPred = pred.getPred();
if (innerPred != null) {
relConstraints.add(innerPred);
requiredPredicates.add(pred);
}
}
} else if (cons instanceof CrySLConstraint) {
ISLConstraint right = ((CrySLConstraint) cons).getRight();
if (right instanceof CrySLPredicate && !predefinedPreds.contains(((CrySLPredicate) right).getPredName())) {
requiredPredicates.add(collectAlternativePredicates((CrySLConstraint) cons, null));
} else {
relConstraints.add(cons);
}
} else {
relConstraints.add(cons);
}
}
}
this.reporter = crySLResultsReporter;
}
private ISLConstraint collectAlternativePredicates(CrySLConstraint cons, AlternativeReqPredicate alt) {
CrySLPredicate right = (CrySLPredicate) cons.getRight();
if (alt == null) {
alt = new AlternativeReqPredicate(right, right.getLocation());
} else {
alt.addAlternative(right);
}
if (cons.getLeft() instanceof CrySLPredicate) {
alt.addAlternative((CrySLPredicate) cons.getLeft());
} else {
return collectAlternativePredicates((CrySLConstraint) cons.getLeft(), alt);
}
return alt;
}
private RequiredCrySLPredicate retrieveValuesForPred(ISLConstraint cons) {
CrySLPredicate pred = (CrySLPredicate) cons;
for (CallSiteWithParamIndex cwpi : this.parameterAnalysisQuerySites) {
for (ICrySLPredicateParameter p : pred.getParameters()) {
// TODO: FIX Cipher rule
if (p.getName().equals("transformation"))
continue;
if (cwpi.getVarName().equals(p.getName())) {
return new RequiredCrySLPredicate(pred, cwpi.stmt());
}
}
}
return null;
}
private static String retrieveConstantFromValue(Value val) {
if (val instanceof StringConstant) {
return ((StringConstant) val).value;
} else if (val instanceof IntConstant || val.getType() instanceof IntType) {
return val.toString();
} else if (val instanceof LongConstant) {
return val.toString().replaceAll("L", "");
} else {
return "";
}
}
public int evaluateRelConstraints() {
int fail = 0;
for (ISLConstraint con : relConstraints) {
EvaluableConstraint currentConstraint = createConstraint(con);
currentConstraint.evaluate();
for (AbstractError e : currentConstraint.getErrors()) {
if (e instanceof ImpreciseValueExtractionError) {
reporter.reportError(object, new ImpreciseValueExtractionError(con, e.getErrorLocation(), e.getRule()));
break;
} else {
fail++;
reporter.reportError(object, e);
}
}
}
return fail;
}
public EvaluableConstraint createConstraint(ISLConstraint con) {
if (con instanceof CrySLComparisonConstraint) {
return new ComparisonConstraint((CrySLComparisonConstraint) con);
} else if (con instanceof CrySLValueConstraint) {
return new ValueConstraint((CrySLValueConstraint) con);
} else if (con instanceof CrySLPredicate) {
return new PredicateConstraint((CrySLPredicate) con);
} else if (con instanceof CrySLConstraint) {
return new BinaryConstraint((CrySLConstraint) con);
}
return null;
}
/**
* @return the allConstraints
*/
public List<ISLConstraint> getAllConstraints() {
return allConstraints;
}
/**
* @return the relConstraints
*/
public Set<ISLConstraint> getRelConstraints() {
return relConstraints;
}
private class BinaryConstraint extends EvaluableConstraint {
public BinaryConstraint(CrySLConstraint c) {
super(c);
}
@Override
public void evaluate() {
CrySLConstraint binaryConstraint = (CrySLConstraint) origin;
EvaluableConstraint left = createConstraint(binaryConstraint.getLeft());
EvaluableConstraint right = createConstraint(binaryConstraint.getRight());
left.evaluate();
LogOps ops = binaryConstraint.getOperator();
if (ops.equals(LogOps.implies)) {
if (left.hasErrors()) {
return;
} else {
right.evaluate();
errors.addAll(right.getErrors());
return;
}
} else if (ops.equals(LogOps.or)) {
right.evaluate();
errors.addAll(left.getErrors());
errors.addAll(right.getErrors());
return;
} else if (ops.equals(LogOps.and)) {
if (left.hasErrors()) {
errors.addAll(left.getErrors());
return;
} else {
right.evaluate();
errors.addAll(right.getErrors());
return;
}
} else if (ops.equals(LogOps.eq)) {
right.evaluate();
if ((left.hasErrors() && right.hasErrors()) || (!left.hasErrors() && !right.hasErrors())) {
return;
} else {
errors.addAll(right.getErrors());
return;
}
}
errors.addAll(left.getErrors());
}
}
public class PredicateConstraint extends EvaluableConstraint {
public PredicateConstraint(CrySLPredicate c) {
super(c);
}
@Override
public void evaluate() {
CrySLPredicate predicateConstraint = (CrySLPredicate) origin;
String predName = predicateConstraint.getPredName();
if (predefinedPreds.contains(predName)) {
handlePredefinedNames(predicateConstraint);
}
}
private void handlePredefinedNames(CrySLPredicate pred) {
List<ICrySLPredicateParameter> parameters = pred.getParameters();
switch (pred.getPredName()) {
case "callTo":
List<ICrySLPredicateParameter> predMethods = parameters;
for (ICrySLPredicateParameter predMethod : predMethods) {
// check whether predMethod is in foundMethods, which type-state analysis has to figure out
CrySLMethod reqMethod = (CrySLMethod) predMethod;
for (Statement unit : collectedCalls) {
if (!(unit.isCallsite()))
continue;
SootMethod foundCall = ((Stmt) unit.getUnit().get()).getInvokeExpr().getMethod();
Collection<SootMethod> convert = CrySLMethodToSootMethod.v().convert(reqMethod);
if (convert.contains(foundCall)) {
return;
}
}
}
// TODO: Need seed here.
return;
case "noCallTo":
if (collectedCalls.isEmpty()) {
return;
}
List<ICrySLPredicateParameter> predForbiddenMethods = parameters;
for (ICrySLPredicateParameter predForbMethod : predForbiddenMethods) {
// check whether predForbMethod is in foundForbMethods, which forbidden-methods analysis has to figure out
CrySLMethod reqMethod = ((CrySLMethod) predForbMethod);
for (Statement call : collectedCalls) {
if (!call.isCallsite())
continue;
SootMethod foundCall = call.getUnit().get().getInvokeExpr().getMethod();
Collection<SootMethod> convert = CrySLMethodToSootMethod.v().convert(reqMethod);
if (convert.contains(foundCall)) {
errors.add(new ForbiddenMethodError(call, classSpec.getRule(), foundCall, convert));
return;
}
}
}
return;
case "neverTypeOf":
// pred looks as follows: neverTypeOf($varName, $type)
// -> first parameter is always the variable
// -> second parameter is always the type
String varName = ((CrySLObject) parameters.get(0)).getVarName();
for (CallSiteWithParamIndex cs : parameterAnalysisQuerySites) {
if (cs.getVarName().equals(varName)) {
Collection<Type> vals = propagatedTypes.get(cs);
for (Type t : vals) {
if (t.toQuotedString().equals(parameters.get(1).getName())) {
for (ExtractedValue v : parsAndVals.get(cs)) {
errors.add(new NeverTypeOfError(new CallSiteWithExtractedValue(cs, v), classSpec.getRule(), object, pred));
}
return;
}
}
}
}
return;
case "length":
// TODO Not implemented!
return;
case "notHardCoded":
CrySLObject varNotToBeHardCoded = (CrySLObject) pred.getParameters().get(0);
String name = varNotToBeHardCoded.getVarName();
String type = varNotToBeHardCoded.getJavaType();
for (CallSiteWithParamIndex cs : parsAndVals.keySet()) {
if (cs.getVarName().equals(name)) {
Collection<ExtractedValue> values = parsAndVals.get(cs);
for (ExtractedValue v : values) {
if (isSubType(type, v.getValue().getType().toQuotedString()) && (isHardCoded(v) || isHardCodedArray(extractSootArray(cs, v)))) {
errors.add(new HardCodedError(new CallSiteWithExtractedValue(cs, v), classSpec.getRule(), object, pred));
}
}
}
}
return;
case "instanceOf":
varName = ((CrySLObject) parameters.get(0)).getVarName();
for (CallSiteWithParamIndex cs : parameterAnalysisQuerySites) {
if (cs.getVarName().equals(varName)) {
Collection<Type> vals = propagatedTypes.get(cs);
if (!vals.parallelStream().anyMatch(e -> isSubType(e.toQuotedString(), parameters.get(1).getName()) || isSubType(parameters.get(1).getName(), e.toQuotedString()))) {
for (ExtractedValue v : parsAndVals.get(cs)) {
errors.add(new InstanceOfError(new CallSiteWithExtractedValue(cs, v), classSpec.getRule(), object, pred));
}
}
}
}
return;
default:
return;
}
}
private boolean isHardCodedArray(Map<String, CallSiteWithExtractedValue> extractSootArray) {
return !(extractSootArray.keySet().size() == 1 && extractSootArray.containsKey(""));
}
}
public class ComparisonConstraint extends EvaluableConstraint {
public ComparisonConstraint(CrySLComparisonConstraint c) {
super(c);
}
@Override
public void evaluate() {
CrySLComparisonConstraint compConstraint = (CrySLComparisonConstraint) origin;
Map<Integer, CallSiteWithExtractedValue> left = evaluate(compConstraint.getLeft());
Map<Integer, CallSiteWithExtractedValue> right = evaluate(compConstraint.getRight());
for (Entry<Integer, CallSiteWithExtractedValue> entry : right.entrySet()) {
if (entry.getKey() == Integer.MIN_VALUE) {
errors.add(new ConstraintError(entry.getValue(), classSpec.getRule(), object, compConstraint));
return;
}
}
for (Entry<Integer, CallSiteWithExtractedValue> leftie : left.entrySet()) {
if (leftie.getKey() == Integer.MIN_VALUE) {
errors.add(new ConstraintError(leftie.getValue(), classSpec.getRule(), object, compConstraint));
return;
}
for (Entry<Integer, CallSiteWithExtractedValue> rightie : right.entrySet()) {
boolean cons = true;
switch (compConstraint.getOperator()) {
case eq:
cons = leftie.getKey().equals(rightie.getKey());
break;
case g:
cons = leftie.getKey() > rightie.getKey();
break;
case ge:
cons = leftie.getKey() >= rightie.getKey();
break;
case l:
cons = leftie.getKey() < rightie.getKey();
break;
case le:
cons = leftie.getKey() <= rightie.getKey();
break;
case neq:
cons = leftie.getKey() != rightie.getKey();
break;
default:
cons = false;
}
if (!cons) {
errors.add(new ConstraintError(leftie.getValue(), classSpec.getRule(), object, origin));
return;
}
}
}
}
private Map<Integer, CallSiteWithExtractedValue> evaluate(CrySLArithmeticConstraint arith) {
Map<Integer, CallSiteWithExtractedValue> left = extractValueAsInt(arith.getLeft(), arith);
Map<Integer, CallSiteWithExtractedValue> right = extractValueAsInt(arith.getRight(), arith);
for (Entry<Integer, CallSiteWithExtractedValue> rightie : right.entrySet()) {
if (rightie.getKey() == Integer.MIN_VALUE) {
return left;
}
}
Map<Integer, CallSiteWithExtractedValue> results = new HashMap<>();
for (Entry<Integer, CallSiteWithExtractedValue> leftie : left.entrySet()) {
if (leftie.getKey() == Integer.MIN_VALUE) {
return left;
}
for (Entry<Integer, CallSiteWithExtractedValue> rightie : right.entrySet()) {
int sum = 0;
switch (arith.getOperator()) {
case n:
sum = leftie.getKey() - rightie.getKey();
break;
case p:
sum = leftie.getKey() + rightie.getKey();
break;
case m:
sum = leftie.getKey() % rightie.getKey();
break;
default:
sum = 0;
}
if (rightie.getValue() != null) {
results.put(sum, rightie.getValue());
} else {
results.put(sum, leftie.getValue());
}
}
}
return results;
}
private Map<Integer, CallSiteWithExtractedValue> extractValueAsInt(ICrySLPredicateParameter par, CrySLArithmeticConstraint arith) {
if (par instanceof CrySLPredicate) {
PredicateConstraint predicateConstraint = new PredicateConstraint((CrySLPredicate) par);
predicateConstraint.evaluate();
if (!predicateConstraint.getErrors().isEmpty()) {
for (AbstractError err : predicateConstraint.getErrors()) {
errors.add(new ImpreciseValueExtractionError(arith, err.getErrorLocation(), err.getRule()));
}
predicateConstraint.errors.clear();
}
return new HashMap<Integer, CallSiteWithExtractedValue>();
} else {
return extractValueAsInt(par.getName(), arith);
}
}
private Map<Integer, CallSiteWithExtractedValue> extractValueAsInt(String exp, ISLConstraint cons) {
final HashMap<Integer, CallSiteWithExtractedValue> valuesInt = new HashMap<>();
// 0. exp may be true or false
if (exp.equalsIgnoreCase("true")) {
valuesInt.put(1, null);
return valuesInt;
}
if (exp.equalsIgnoreCase("false")) {
valuesInt.put(0, null);
return valuesInt;
}
try {
// 1. exp may (already) be an integer
valuesInt.put(Integer.parseInt(exp), null);
return valuesInt;
}
catch (NumberFormatException ex) {
// 2. If not, it's a variable name.
// Get value of variable left from map
final Map<String, CallSiteWithExtractedValue> valueCollection = extractValueAsString(exp, cons);
if (valueCollection.isEmpty()) {
return valuesInt;
}
try {
for (Entry<String, CallSiteWithExtractedValue> value : valueCollection.entrySet()) {
if(value.getKey().equals("true"))
valuesInt.put(1, value.getValue());
else if(value.getKey().equals("false"))
valuesInt.put(0, value.getValue());
else
valuesInt.put(Integer.parseInt(value.getKey()), value.getValue());
}
}
catch (NumberFormatException ex1) {
// If that does not work either, I'm out of ideas ...
LOGGER.error("An exception occured when extracting value as Integer.", ex1);
}
return valuesInt;
}
}
}
public class ValueConstraint extends EvaluableConstraint {
public ValueConstraint(CrySLValueConstraint c) {
super(c);
}
@Override
public void evaluate() {
CrySLValueConstraint valCons = (CrySLValueConstraint) origin;
CrySLObject var = valCons.getVar();
final List<Entry<String, CallSiteWithExtractedValue>> vals = getValFromVar(var, valCons);
if (vals.isEmpty()) {
// TODO: Check whether this works as desired
return;
}
for (Entry<String, CallSiteWithExtractedValue> val : vals) {
List<String> values = valCons.getValueRange().parallelStream().map(e -> e.toLowerCase()).collect(Collectors.toList());
if (!values.contains(val.getKey().toLowerCase())) {
errors.add(new ConstraintError(val.getValue(), classSpec.getRule(), object, valCons));
}
}
return;
}
private List<Entry<String, CallSiteWithExtractedValue>> getValFromVar(CrySLObject var, ISLConstraint cons) {
final String varName = var.getVarName();
final Map<String, CallSiteWithExtractedValue> valueCollection = extractValueAsString(varName, cons);
List<Entry<String, CallSiteWithExtractedValue>> vals = new ArrayList<>();
if (valueCollection.isEmpty()) {
return vals;
}
for (Entry<String, CallSiteWithExtractedValue> e : valueCollection.entrySet()) {
CrySLSplitter splitter = var.getSplitter();
final CallSiteWithExtractedValue location = e.getValue();
String val = e.getKey();
if (splitter != null) {
int ind = splitter.getIndex();
String splitElement = splitter.getSplitter();
if (ind > 0) {
String[] splits = val.split(splitElement);
if (splits.length > ind) {
vals.add(new AbstractMap.SimpleEntry<>(splits[ind], location));
} else {
vals.add(new AbstractMap.SimpleEntry<>("", location));
}
} else {
vals.add(new AbstractMap.SimpleEntry<>(val.split(splitElement)[ind], location));
}
} else {
vals.add(new AbstractMap.SimpleEntry<>(val, location));
}
}
return vals;
}
}
public abstract class EvaluableConstraint {
Set<AbstractError> errors = Sets.newHashSet();
ISLConstraint origin;
public abstract void evaluate();
public EvaluableConstraint(ISLConstraint con) {
origin = con;
}
protected Collection<AbstractError> getErrors() {
return errors;
};
public boolean hasErrors() {
return !errors.isEmpty();
}
protected Map<String, CallSiteWithExtractedValue> extractValueAsString(String varName, ISLConstraint cons) {
Map<String, CallSiteWithExtractedValue> varVal = Maps.newHashMap();
for (CallSiteWithParamIndex wrappedCallSite : parsAndVals.keySet()) {
final Stmt callSite = wrappedCallSite.stmt().getUnit().get();
for (ExtractedValue wrappedAllocSite : parsAndVals.get(wrappedCallSite)) {
final Stmt allocSite = wrappedAllocSite.stmt().getUnit().get();
if (wrappedCallSite.getVarName().equals(varName)) {
InvokeExpr invoker = callSite.getInvokeExpr();
if (callSite.equals(allocSite)) {
varVal.put(retrieveConstantFromValue(invoker.getArg(wrappedCallSite.getIndex())), new CallSiteWithExtractedValue(wrappedCallSite, wrappedAllocSite));
} else if (allocSite instanceof AssignStmt) {
if (wrappedAllocSite.getValue() instanceof Constant) {
// varVal.put(retrieveConstantFromValue(wrappedAllocSite.getValue()), new CallSiteWithExtractedValue(wrappedCallSite, wrappedAllocSite));
String retrieveConstantFromValue = retrieveConstantFromValue(wrappedAllocSite.getValue());
int pos = -1;
for (int i = 0; i < invoker.getArgs().size(); i++) {
if (((AssignStmt) allocSite).getLeftOpBox().getValue().toString().equals(invoker.getArgs().get(i).toString())) {
pos = i;
}
}
if (pos > -1 && "boolean".equals(invoker.getMethodRef().getParameterType(pos).toQuotedString())) {
varVal.put("0".equals(retrieveConstantFromValue) ? "false" : "true", new CallSiteWithExtractedValue(wrappedCallSite, wrappedAllocSite));
} else {
varVal.put(retrieveConstantFromValue, new CallSiteWithExtractedValue(wrappedCallSite, wrappedAllocSite));
}
} else if (wrappedAllocSite.getValue() instanceof JNewArrayExpr) {
varVal.putAll(extractSootArray(wrappedCallSite, wrappedAllocSite));
}
}
}
}
}
return varVal;
}
/***
* Function that finds the values assigned to a soot array.
* @param callSite call site at which sootValue is involved
* @param allocSite allocation site at which sootValue is involved
* @param arrayLocal soot array local variable for which values are to be found
* @return extracted array values
*/
protected Map<String, CallSiteWithExtractedValue> extractSootArray(CallSiteWithParamIndex callSite, ExtractedValue allocSite){
Value arrayLocal = allocSite.getValue();
Body methodBody = allocSite.stmt().getMethod().getActiveBody();
Map<String, CallSiteWithExtractedValue> arrVal = Maps.newHashMap();
if (methodBody != null) {
Iterator<Unit> unitIterator = methodBody.getUnits().snapshotIterator();
while (unitIterator.hasNext()) {
final Unit unit = unitIterator.next();
if (unit instanceof AssignStmt) {
AssignStmt uStmt = (AssignStmt) (unit);
Value leftValue = uStmt.getLeftOp();
Value rightValue = uStmt.getRightOp();
if (leftValue.toString().contains(arrayLocal.toString()) && !rightValue.toString().contains("newarray")) {
arrVal.put(retrieveConstantFromValue(rightValue), new CallSiteWithExtractedValue(callSite, allocSite));
}
}
}
}
return arrVal;
}
}
public List<ISLConstraint> getRequiredPredicates() {
return requiredPredicates;
}
protected boolean isSubType(String typeOne, String typeTwo) {
boolean subTypes = typeOne.equals(typeTwo);
subTypes |= (typeOne + "[]").equals(typeTwo);
if (!subTypes) {
try {
subTypes = Class.forName(typeOne).isAssignableFrom(Class.forName(typeTwo));
}
catch (ClassNotFoundException e) {}
}
return subTypes;
}
public boolean isHardCoded(ExtractedValue val) {
return val.getValue() instanceof IntConstant || val.getValue() instanceof StringConstant || (val.getValue() instanceof NewExpr && ((NewExpr) val.getValue()).getType().toString().equals("java.math.BigInteger"));
}
}
| 24,782 | 34.454936 | 212 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/cryslhandler/CrySLModelReader.java | package crypto.cryslhandler;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.base.CharMatcher;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.inject.Injector;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.common.types.JvmExecutable;
import org.eclipse.xtext.common.types.JvmFormalParameter;
import org.eclipse.xtext.common.types.access.impl.ClasspathTypeProvider;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import crypto.exceptions.CryptoAnalysisException;
import com.google.common.base.CharMatcher;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Injector;
import crypto.interfaces.ICrySLPredicateParameter;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLArithmeticConstraint;
import crypto.rules.CrySLArithmeticConstraint.ArithOp;
import crypto.rules.CrySLComparisonConstraint;
import crypto.rules.CrySLComparisonConstraint.CompOp;
import crypto.rules.CrySLCondPredicate;
import crypto.rules.CrySLConstraint;
import crypto.rules.CrySLConstraint.LogOps;
import crypto.rules.CrySLForbiddenMethod;
import crypto.rules.CrySLMethod;
import crypto.rules.CrySLObject;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLRule;
import crypto.rules.CrySLSplitter;
import crypto.rules.CrySLValueConstraint;
import crypto.rules.ParEqualsPredicate;
import crypto.rules.StateMachineGraph;
import crypto.rules.StateNode;
import crypto.rules.TransitionEdge;
import de.darmstadt.tu.crossing.CrySLStandaloneSetup;
import de.darmstadt.tu.crossing.constraints.CrySLArithmeticOperator;
import de.darmstadt.tu.crossing.constraints.CrySLComparisonOperator;
import de.darmstadt.tu.crossing.constraints.CrySLLogicalOperator;
import de.darmstadt.tu.crossing.crySL.ArithmeticExpression;
import de.darmstadt.tu.crossing.crySL.ArithmeticOperator;
import de.darmstadt.tu.crossing.crySL.ArrayElements;
import de.darmstadt.tu.crossing.crySL.ComparingOperator;
import de.darmstadt.tu.crossing.crySL.ComparisonExpression;
import de.darmstadt.tu.crossing.crySL.Constraint;
import de.darmstadt.tu.crossing.crySL.DestroysBlock;
import de.darmstadt.tu.crossing.crySL.Domainmodel;
import de.darmstadt.tu.crossing.crySL.EnsuresBlock;
import de.darmstadt.tu.crossing.crySL.Event;
import de.darmstadt.tu.crossing.crySL.Expression;
import de.darmstadt.tu.crossing.crySL.ForbMethod;
import de.darmstadt.tu.crossing.crySL.ForbiddenBlock;
import de.darmstadt.tu.crossing.crySL.Literal;
import de.darmstadt.tu.crossing.crySL.LiteralExpression;
import de.darmstadt.tu.crossing.crySL.LogicalImply;
import de.darmstadt.tu.crossing.crySL.LogicalOperator;
import de.darmstadt.tu.crossing.crySL.Object;
import de.darmstadt.tu.crossing.crySL.ObjectDecl;
import de.darmstadt.tu.crossing.crySL.Order;
import de.darmstadt.tu.crossing.crySL.PreDefinedPredicates;
import de.darmstadt.tu.crossing.crySL.Pred;
import de.darmstadt.tu.crossing.crySL.PredLit;
import de.darmstadt.tu.crossing.crySL.ReqPred;
import de.darmstadt.tu.crossing.crySL.RequiredBlock;
import de.darmstadt.tu.crossing.crySL.SimpleOrder;
import de.darmstadt.tu.crossing.crySL.SuPar;
import de.darmstadt.tu.crossing.crySL.SuParList;
import de.darmstadt.tu.crossing.crySL.SuperType;
import de.darmstadt.tu.crossing.crySL.UnaryPreExpression;
import de.darmstadt.tu.crossing.crySL.UseBlock;
import de.darmstadt.tu.crossing.crySL.impl.DomainmodelImpl;
import de.darmstadt.tu.crossing.crySL.impl.ObjectImpl;
public class CrySLModelReader {
private List<CrySLForbiddenMethod> forbiddenMethods = null;
private StateMachineGraph smg = null;
private XtextResourceSet resourceSet;
public static final String cryslFileEnding = ".crysl";
private static final String INT = "int";
private static final String THIS = "this";
private static final String ANY_TYPE = "AnyType";
private static final String NULL = "null";
private static final String UNDERSCORE = "_";
/**
* Creates a CrySLModelReader
* @throws MalformedURLException
*/
public CrySLModelReader() throws MalformedURLException {
CrySLStandaloneSetup crySLStandaloneSetup = new CrySLStandaloneSetup();
final Injector injector = crySLStandaloneSetup.createInjectorAndDoEMFRegistration();
this.resourceSet = injector.getInstance(XtextResourceSet.class);
String a = System.getProperty("java.class.path");
String[] l = a.split(";");
URL[] classpath = new URL[l.length];
for (int i = 0; i < classpath.length; i++) {
classpath[i] = new File(l[i]).toURI().toURL();
}
URLClassLoader ucl = new URLClassLoader(classpath);
this.resourceSet.setClasspathURIContext(new URLClassLoader(classpath));
new ClasspathTypeProvider(ucl, this.resourceSet, null, null);
this.resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
}
/**
* Reads the content of a CrySL file from an {@link InputStream}, afterwards the {@link CrySLRule} will be created.
*
* @param stream the {@link InputStream} holds the CrySL file content
* @param virtualFileName the name needs following structure [HexHashedAbsoluteZipFilePath][SystemFileSeparator][ZipEntryName]
* @return the {@link CrySLRule}
* @throws IllegalArgumentException, IOException
* @throws CryptoAnalysisException
*/
public CrySLRule readRule(InputStream stream, String virtualFileName) throws IllegalArgumentException, IOException, CryptoAnalysisException{
if (!virtualFileName.endsWith(cryslFileEnding)) {
throw new CryptoAnalysisException ("The prefix of "+virtualFileName+" does not correspond to "+cryslFileEnding);
}
URI uri = URI.createURI(virtualFileName);
Resource resource= resourceSet.getURIResourceMap().get(uri);
if (resource == null){
resource = resourceSet.createResource(uri);
resource.load(stream, Collections.EMPTY_MAP);
}
return createRuleFromResource(resource);
}
/**
* Reads the content of a CrySL file and returns a {@link CrySLRule} object.
*
* @param ruleFile the CrySL file
* @return the {@link CrySLRule} object
* @throws CryptoAnalysisException
*/
public CrySLRule readRule(File ruleFile) throws CryptoAnalysisException {
final String fileName = ruleFile.getName();
// Re-included this code because cryslFileEnding is dotted ".crysl".
// And because this is a public constant, I'm scared to change it, as it may cause massive versioning problems.
final String extension = fileName.substring(fileName.lastIndexOf("."));
if (!cryslFileEnding.equals(extension)) {
if (!fileName.endsWith(cryslFileEnding))
return null;
}
if (!extension.equals(cryslFileEnding)) {
throw new CryptoAnalysisException("The prefix of "+ fileName + " does not correspond to "+ cryslFileEnding);
}
final Resource resource = resourceSet.getResource(URI.createFileURI(ruleFile.getAbsolutePath()), true);// URI.createPlatformResourceURI(ruleFile.getFullPath().toPortableString(), // true), true);
return createRuleFromResource(resource);
}
private CrySLRule createRuleFromResource(Resource resource) throws CryptoAnalysisException {
if (resource == null)
throw new CryptoAnalysisException("Internal error creating a CrySL rule: 'resource parameter was null'.");
final EObject eObject = resource.getContents().get(0);
final Domainmodel dm = (Domainmodel) eObject;
String curClass = dm.getJavaType().getQualifiedName();
final RequiredBlock events = dm.getReq_events();
final EnsuresBlock ensure = dm.getEnsure();
final Map<ParEqualsPredicate, SuperType> pre_preds = Maps.newHashMap();
final DestroysBlock destroys = dm.getDestroy();
Expression order = dm.getOrder();
if (order instanceof Order) {
validateOrder((Order) order);
}
if (destroys != null) {
pre_preds.putAll(getKills(destroys.getPred()));
}
if (ensure != null) {
pre_preds.putAll(getPredicates(ensure.getPred()));
}
this.smg = (new StateMachineGraphBuilder(order, events)).buildSMG();
final ForbiddenBlock forbEvent = dm.getForbEvent();
this.forbiddenMethods = (forbEvent != null) ? getForbiddenMethods(forbEvent.getForb_methods()) : Lists.newArrayList();
final List<ISLConstraint> constraints = (dm.getReqConstraints() != null) ? buildUpConstraints(dm.getReqConstraints().getReq()) : Lists.newArrayList();
constraints.addAll(((dm.getRequire() != null) ? collectRequiredPredicates(dm.getRequire().getPred()) : Lists.newArrayList()));
final List<Entry<String, String>> objects = getObjects(dm.getUsage());
final List<CrySLPredicate> actPreds = Lists.newArrayList();
for (final ParEqualsPredicate pred : pre_preds.keySet()) {
final SuperType cond = pre_preds.get(pred);
if (cond == null) {
actPreds.add(pred.tobasicPredicate());
} else {
actPreds.add(new CrySLCondPredicate(pred.getBaseObject(), pred.getPredName(), pred.getParameters(), pred.isNegated(),
getStatesForMethods(CryslReaderUtils.resolveAggregateToMethodeNames(cond)), pred.getConstraint()));
}
}
return new CrySLRule(curClass, objects, this.forbiddenMethods, this.smg, constraints, actPreds);
}
private void validateOrder(Order order) {
List<String> collected = new ArrayList<String>();
collected.addAll(collectLabelsFromExpression(order.getLeft()));
collected.addAll(collectLabelsFromExpression(order.getRight()));
}
private List<String> collectLabelsFromExpression(Expression exp) {
List<String> collected = new ArrayList<String>();
if (exp instanceof Order || exp instanceof SimpleOrder) {
collected.addAll(collectLabelsFromExpression(exp.getLeft()));
collected.addAll(collectLabelsFromExpression(exp.getRight()));
} else {
for (Event ev : exp.getOrderEv()) {
if (ev instanceof SuperType) {
if (ev instanceof de.darmstadt.tu.crossing.crySL.Aggregate) {
for (Event lab : ((de.darmstadt.tu.crossing.crySL.Aggregate) ev).getLab()) {
if (lab instanceof SuperType) {
collected.add(((SuperType) lab).getName());
} else {
throw new ClassCastException("Parser error in the line after definition of label " + collected.get(collected.size() - 1));
}
}
} else {
collected.add(((SuperType) ev).getName());
}
}
}
}
return collected;
}
private Map<? extends ParEqualsPredicate, ? extends SuperType> getKills(final EList<Constraint> eList) {
final Map<ParEqualsPredicate, SuperType> preds = new HashMap<>();
for (final Constraint cons : eList) {
String curClass = ((DomainmodelImpl) cons.eContainer().eContainer()).getJavaType().getQualifiedName();
final Pred pred = (Pred) cons.getPredLit().getPred();
final List<ICrySLPredicateParameter> variables = new ArrayList<>();
if (pred.getParList() != null) {
boolean firstPar = true;
for (final SuPar var : pred.getParList().getParameters()) {
if (var.getVal() != null) {
final ObjectImpl object = (ObjectImpl) ((LiteralExpression) var.getVal().getLit().getName()).getValue();
String name = object.getName();
String type = ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName();
if (name == null) {
name = THIS;
type = curClass;
}
variables.add(new CrySLObject(name, type));
} else {
if (firstPar) {
variables.add(new CrySLObject(THIS, curClass));
} else {
variables.add(new CrySLObject(UNDERSCORE, NULL));
}
}
firstPar = false;
}
}
final String meth = pred.getPredName();
final SuperType cond = cons.getLabelCond();
if (cond == null) {
preds.put(new ParEqualsPredicate(null, meth, variables, true), null);
} else {
preds.put(new ParEqualsPredicate(null, meth, variables, true), cond);
}
}
return preds;
}
private Map<? extends ParEqualsPredicate, ? extends SuperType> getPredicates(final List<Constraint> predList) {
final Map<ParEqualsPredicate, SuperType> preds = new HashMap<>();
for (final Constraint cons : predList) {
final Pred pred = (Pred) cons.getPredLit().getPred();
String curClass = ((DomainmodelImpl) cons.eContainer().eContainer()).getJavaType().getQualifiedName();
final List<ICrySLPredicateParameter> variables = new ArrayList<>();
if (pred.getParList() != null) {
boolean firstPar = true;
for (final SuPar var : pred.getParList().getParameters()) {
if (var.getVal() != null) {
final ObjectImpl object = (ObjectImpl) ((LiteralExpression) var.getVal().getLit().getName()).getValue();
String type = ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName();
String name = object.getName();
if (name == null) {
name = THIS;
type = curClass;
}
variables.add(new CrySLObject(name, type));
} else {
if (firstPar) {
variables.add(new CrySLObject(THIS, curClass));
} else {
variables.add(new CrySLObject(UNDERSCORE, NULL));
}
}
firstPar = false;
}
}
final CrySLPredicate ensPredCons = extractReqPred(cons.getPredLit());
final String meth = pred.getPredName();
final SuperType cond = cons.getLabelCond();
if (cond == null) {
preds.put(new ParEqualsPredicate(null, meth, variables, false, ensPredCons.getConstraint()), null);
} else {
preds.put(new ParEqualsPredicate(null, meth, variables, false, ensPredCons.getConstraint()), cond);
}
}
return preds;
}
private List<ISLConstraint> buildUpConstraints(final List<Constraint> constraints) {
final List<ISLConstraint> slCons = new ArrayList<>();
for (final Constraint cons : constraints) {
final ISLConstraint constraint = getConstraint(cons);
if (constraint != null) {
slCons.add(constraint);
}
}
return slCons;
}
private ISLConstraint getConstraint(final Constraint cons) {
if (cons == null) {
return null;
}
ISLConstraint slci = null;
if (cons instanceof ArithmeticExpression) {
final ArithmeticExpression ae = (ArithmeticExpression) cons;
String op = new CrySLArithmeticOperator((ArithmeticOperator) ae.getOperator()).toString();
ArithOp operator = ArithOp.n;
if ("+".equals(op)) {
operator = ArithOp.p;
}
ObjectDecl leftObj =
(ObjectDecl) ((ObjectImpl) ((LiteralExpression) ((LiteralExpression) ((LiteralExpression) ae.getLeftExpression()).getCons()).getName()).getValue()).eContainer();
CrySLObject leftSide = new CrySLObject(leftObj.getObjectName().getName(), leftObj.getObjectType().getQualifiedName());
ObjectDecl rightObj =
(ObjectDecl) ((ObjectImpl) ((LiteralExpression) ((LiteralExpression) ((LiteralExpression) ae.getRightExpression()).getCons()).getName()).getValue()).eContainer();
CrySLObject rightSide = new CrySLObject(rightObj.getObjectName().getName(), rightObj.getObjectType().getQualifiedName());
slci = new CrySLArithmeticConstraint(leftSide, rightSide, operator);
} else if (cons instanceof LiteralExpression) {
final LiteralExpression lit = (LiteralExpression) cons;
final List<String> parList = new ArrayList<>();
if (lit.getLitsleft() != null) {
for (final Literal a : lit.getLitsleft().getParameters()) {
parList.add(filterQuotes(a.getVal()));
}
}
if (lit.getCons() instanceof PreDefinedPredicates) {
slci = getPredefinedPredicate(lit);
} else {
final String part = ((ArrayElements) lit.getCons()).getCons().getPart();
if (part != null) {
final LiteralExpression name = (LiteralExpression) ((ArrayElements) lit.getCons()).getCons().getLit().getName();
final SuperType object = name.getValue();
final CrySLObject variable = new CrySLObject(object.getName(), ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName(),
new CrySLSplitter(Integer.parseInt(((ArrayElements) lit.getCons()).getCons().getInd()), filterQuotes(((ArrayElements) lit.getCons()).getCons().getSplit())));
slci = new CrySLValueConstraint(variable, parList);
} else {
final String consPred = ((ArrayElements) lit.getCons()).getCons().getConsPred();
if (consPred != null) {
final LiteralExpression name = (LiteralExpression) ((ArrayElements) lit.getCons()).getCons().getLit().getName();
final SuperType object = name.getValue();
int ind;
if (consPred.equals("alg(")) {
ind = 0;
final CrySLObject variable =
new CrySLObject(object.getName(), ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName(), new CrySLSplitter(ind, filterQuotes("/")));
slci = new CrySLValueConstraint(variable, parList);
} else if (consPred.equals("mode(")) {
ind = 1;
final CrySLObject variable =
new CrySLObject(object.getName(), ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName(), new CrySLSplitter(ind, filterQuotes("/")));
slci = new CrySLValueConstraint(variable, parList);
} else if (consPred.equals("pad(")) {
ind = 2;
final CrySLObject variable =
new CrySLObject(object.getName(), ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName(), new CrySLSplitter(ind, filterQuotes("/")));
slci = new CrySLValueConstraint(variable, parList);
}
} else {
LiteralExpression name = (LiteralExpression) ((ArrayElements) lit.getCons()).getCons().getName();
if (name == null) {
name = (LiteralExpression) ((ArrayElements) lit.getCons()).getCons().getLit().getName();
}
final SuperType object = name.getValue();
final CrySLObject variable = new CrySLObject(object.getName(), ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName());
slci = new CrySLValueConstraint(variable, parList);
}
}
}
} else if (cons instanceof ComparisonExpression) {
final ComparisonExpression comp = (ComparisonExpression) cons;
CompOp op = null;
switch ((new CrySLComparisonOperator((ComparingOperator) comp.getOperator())).toString()) {
case ">":
op = CompOp.g;
break;
case "<":
op = CompOp.l;
break;
case ">=":
op = CompOp.ge;
break;
case "<=":
op = CompOp.le;
break;
case "!=":
op = CompOp.neq;
break;
default:
op = CompOp.eq;
}
CrySLArithmeticConstraint left;
CrySLArithmeticConstraint right;
final Constraint leftExpression = comp.getLeftExpression();
if (leftExpression instanceof LiteralExpression) {
left = convertLiteralToArithmetic(leftExpression);
} else if (leftExpression instanceof ArithmeticExpression) {
left = convertArithExpressionToArithmeticConstraint(leftExpression);
} else {
left = (CrySLArithmeticConstraint) leftExpression;
}
final Constraint rightExpression = comp.getRightExpression();
if (rightExpression instanceof LiteralExpression) {
right = convertLiteralToArithmetic(rightExpression);
} else {
right = convertArithExpressionToArithmeticConstraint(rightExpression);
}
slci = new CrySLComparisonConstraint(left, right, op);
} else if (cons instanceof UnaryPreExpression) {
final UnaryPreExpression un = (UnaryPreExpression) cons;
final List<ICrySLPredicateParameter> vars = new ArrayList<>();
final Pred innerPredicate = (Pred) un.getEnclosedExpression();
if (innerPredicate.getParList() != null) {
for (final SuPar sup : innerPredicate.getParList().getParameters()) {
vars.add(new CrySLObject(UNDERSCORE, NULL));
}
}
slci = new CrySLPredicate(null, innerPredicate.getPredName(), vars, true);
} else if (cons instanceof Pred) {
if (((Pred) cons).getPredName() != null && !((Pred) cons).getPredName().isEmpty()) {
final List<ICrySLPredicateParameter> vars = new ArrayList<>();
final SuParList parList = ((Pred) cons).getParList();
if (parList != null) {
for (final SuPar sup : parList.getParameters()) {
vars.add(new CrySLObject(UNDERSCORE, NULL));
}
}
slci = new CrySLPredicate(null, ((Pred) cons).getPredName(), vars, false);
}
} else if (cons instanceof Constraint) {
LogOps op = null;
final EObject operator = cons.getOperator();
if (operator instanceof LogicalImply) {
op = LogOps.implies;
} else {
switch ((new CrySLLogicalOperator((LogicalOperator) operator)).toString()) {
case "&&":
op = LogOps.and;
break;
case "||":
op = LogOps.or;
break;
default:
System.err.println("Sign " + operator.toString() + " was not properly translated.");
op = LogOps.and;
}
}
slci = new CrySLConstraint(getConstraint(cons.getLeftExpression()), getConstraint(cons.getRightExpression()), op);
}
return slci;
}
private List<CrySLForbiddenMethod> getForbiddenMethods(final EList<ForbMethod> methods) {
final List<CrySLForbiddenMethod> methodSignatures = new ArrayList<>();
for (final ForbMethod fm : methods) {
final JvmExecutable meth = fm.getJavaMeth();
final List<Entry<String, String>> pars = new ArrayList<>();
for (final JvmFormalParameter par : meth.getParameters()) {
pars.add(new SimpleEntry<>(par.getSimpleName(), par.getParameterType().getSimpleName()));
}
final List<CrySLMethod> crysl = new ArrayList<>();
final Event alternative = fm.getRep();
if (alternative != null) {
crysl.addAll(CryslReaderUtils.resolveAggregateToMethodeNames(alternative));
}
methodSignatures.add(new CrySLForbiddenMethod(
new CrySLMethod(meth.getDeclaringType().getIdentifier() + "." + meth.getSimpleName(), pars, null, new SimpleEntry<>(UNDERSCORE, ANY_TYPE)), false, crysl));
}
return methodSignatures;
}
private List<ISLConstraint> collectRequiredPredicates(final EList<ReqPred> requiredPreds) {
final List<ISLConstraint> preds = new ArrayList<>();
for (final ReqPred pred : requiredPreds) {
ISLConstraint reqPred = null;
if (pred instanceof PredLit) {
reqPred = extractReqPred(pred);
} else {
final ReqPred left = pred.getLeftExpression();
final ReqPred right = pred.getRightExpression();
List<CrySLPredicate> altPreds = retrieveReqPredFromAltPreds(left);
altPreds.add(extractReqPred(right));
reqPred = new CrySLConstraint(altPreds.get(0), altPreds.get(1), LogOps.or);
for (int i = 2; i < altPreds.size(); i++) {
reqPred = new CrySLConstraint(reqPred, altPreds.get(i), LogOps.or);
}
}
preds.add(reqPred);
}
return preds;
}
private List<CrySLPredicate> retrieveReqPredFromAltPreds(ReqPred left) {
List<CrySLPredicate> preds = new ArrayList<CrySLPredicate>();
if (left instanceof PredLit) {
preds.add(extractReqPred(left));
} else {
preds.addAll(retrieveReqPredFromAltPreds(left.getLeftExpression()));
preds.add(extractReqPred(left.getRightExpression()));
}
return preds;
}
private List<Entry<String, String>> getObjects(final UseBlock usage) {
final List<Entry<String, String>> objects = new ArrayList<>();
for (final ObjectDecl obj : usage.getObjects()) {
objects.add(new SimpleEntry<>(obj.getObjectType().getIdentifier(), obj.getObjectName().getName()));
}
return objects;
}
private Set<StateNode> getStatesForMethods(final List<CrySLMethod> condMethods) {
final Set<StateNode> predGens = new HashSet<>();
if (condMethods.size() != 0) {
for (final TransitionEdge methTrans : this.smg.getAllTransitions()) {
final List<CrySLMethod> transLabel = methTrans.getLabel();
if (transLabel.size() > 0 && (transLabel.equals(condMethods) || (condMethods.size() == 1 && transLabel.contains(condMethods.get(0))))) {
predGens.add(methTrans.getRight());
}
}
}
return predGens;
}
private ISLConstraint getPredefinedPredicate(final LiteralExpression lit) {
final String pred = ((PreDefinedPredicates) lit.getCons()).getPredName();
ISLConstraint slci = null;
switch (pred) {
case "callTo":
final List<ICrySLPredicateParameter> methodsToBeCalled = new ArrayList<>();
methodsToBeCalled.addAll(CryslReaderUtils.resolveAggregateToMethodeNames(((PreDefinedPredicates) lit.getCons()).getObj().get(0)));
slci = new CrySLPredicate(null, pred, methodsToBeCalled, false);
break;
case "noCallTo":
final List<ICrySLPredicateParameter> methodsNotToBeCalled = new ArrayList<>();
final List<CrySLMethod> resolvedMethodNames = CryslReaderUtils.resolveAggregateToMethodeNames(((PreDefinedPredicates) lit.getCons()).getObj().get(0));
for (final CrySLMethod csm : resolvedMethodNames) {
this.forbiddenMethods.add(new CrySLForbiddenMethod(csm, true));
methodsNotToBeCalled.add(csm);
}
slci = new CrySLPredicate(null, pred, methodsNotToBeCalled, false);
break;
case "neverTypeOf":
final List<ICrySLPredicateParameter> varNType = new ArrayList<>();
final Object object = (de.darmstadt.tu.crossing.crySL.Object) ((PreDefinedPredicates) lit.getCons()).getObj().get(0);
final String type = ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName();
varNType.add(new CrySLObject(object.getName(), type));
final String qualifiedName = ((PreDefinedPredicates) lit.getCons()).getType().getType().getQualifiedName();
varNType.add(new CrySLObject(qualifiedName, NULL));
slci = new CrySLPredicate(null, pred, varNType, false);
break;
case "length":
final List<ICrySLPredicateParameter> variables = new ArrayList<>();
final Object objectL = (de.darmstadt.tu.crossing.crySL.Object) ((PreDefinedPredicates) lit.getCons()).getObj().get(0);
final String typeL = ((ObjectDecl) objectL.eContainer()).getObjectType().getQualifiedName();
variables.add(new CrySLObject(objectL.getName(), typeL));
slci = new CrySLPredicate(null, pred, variables, false);
break;
case "notHardCoded":
final List<ICrySLPredicateParameter> variables1 = new ArrayList<>();
final Object objectL1 = (de.darmstadt.tu.crossing.crySL.Object) ((PreDefinedPredicates) lit.getCons()).getObj().get(0);
final String typeL1 = ((ObjectDecl) objectL1.eContainer()).getObjectType().getQualifiedName();
variables1.add(new CrySLObject(objectL1.getName(), typeL1));
slci = new CrySLPredicate(null, pred, variables1, false);
break;
case "instanceOf":
final List<ICrySLPredicateParameter> varInstOf = new ArrayList<>();
final Object objInstOf = (de.darmstadt.tu.crossing.crySL.Object) ((PreDefinedPredicates) lit.getCons()).getObj().get(0);
final String instOfType = ((ObjectDecl) objInstOf.eContainer()).getObjectType().getQualifiedName();
varInstOf.add(new CrySLObject(objInstOf.getName(), instOfType));
final String typeName = ((PreDefinedPredicates) lit.getCons()).getType().getType().getQualifiedName();
varInstOf.add(new CrySLObject(typeName, NULL));
slci = new CrySLPredicate(null, pred, varInstOf, false);
break;
default:
new RuntimeException();
}
return slci;
}
private CrySLArithmeticConstraint convertLiteralToArithmetic(final Constraint expression) {
final LiteralExpression cons = (LiteralExpression) ((LiteralExpression) expression).getCons();
ICrySLPredicateParameter name;
if (cons instanceof PreDefinedPredicates) {
name = getPredefinedPredicate((LiteralExpression) expression);
} else {
final EObject constraint = cons.getName();
final String object = getValueOfLiteral(constraint);
if (constraint instanceof LiteralExpression) {
name = new CrySLObject(object, ((ObjectDecl) ((ObjectImpl) ((LiteralExpression) constraint).getValue()).eContainer()).getObjectType().getQualifiedName());
} else {
name = new CrySLObject(object, INT);
}
}
return new CrySLArithmeticConstraint(name, new CrySLObject("0", INT), crypto.rules.CrySLArithmeticConstraint.ArithOp.p);
}
private CrySLArithmeticConstraint convertArithExpressionToArithmeticConstraint(final Constraint expression) {
CrySLArithmeticConstraint right;
final ArithmeticExpression ar = (ArithmeticExpression) expression;
final String leftValue = getValueOfLiteral(ar.getLeftExpression());
final String rightValue = getValueOfLiteral(ar.getRightExpression());
final CrySLArithmeticOperator aop = new CrySLArithmeticOperator((ArithmeticOperator) ar.getOperator());
ArithOp operator = null;
switch (aop.toString()) {
case "+":
operator = ArithOp.p;
break;
case "-":
operator = ArithOp.n;
break;
case "%":
operator = ArithOp.m;
break;
default:
operator = ArithOp.p;
}
right = new CrySLArithmeticConstraint(new CrySLObject(leftValue, getTypeName(ar.getLeftExpression(), leftValue)),
new CrySLObject(rightValue, getTypeName(ar.getRightExpression(), rightValue)), operator);
return right;
}
private CrySLPredicate extractReqPred(final ReqPred pred) {
final List<ICrySLPredicateParameter> variables = new ArrayList<>();
PredLit innerPred = (PredLit) pred;
EObject cons = innerPred.getCons();
ISLConstraint conditional = null;
if (cons instanceof Constraint) {
conditional = getConstraint((Constraint) cons);
} else if (cons instanceof Pred) {
conditional = getPredicate((Pred) cons);
}
if (innerPred.getPred().getParList() != null) {
for (final SuPar var : innerPred.getPred().getParList().getParameters()) {
if (var.getVal() != null) {
final LiteralExpression lit = var.getVal();
final ObjectImpl object = (ObjectImpl) ((LiteralExpression) lit.getLit().getName()).getValue();
final String type = ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName();
final String variable = object.getName();
final String part = var.getVal().getPart();
if (part != null) {
variables.add(new CrySLObject(variable, type, new CrySLSplitter(Integer.parseInt(lit.getInd()), filterQuotes(lit.getSplit()))));
} else {
final String consPred = var.getVal().getConsPred();
int ind;
if (consPred != null) {
if (consPred.equals("alg(")) {
ind = 0;
variables.add(new CrySLObject(variable, type, new CrySLSplitter(ind, filterQuotes("/"))));
} else if (consPred.equals("mode(")) {
ind = 1;
variables.add(new CrySLObject(variable, type, new CrySLSplitter(ind, filterQuotes("/"))));
} else if (consPred.equals("pad(")) {
ind = 2;
variables.add(new CrySLObject(variable, type, new CrySLSplitter(ind, filterQuotes("/"))));
}
} else {
variables.add(new CrySLObject(variable, type));
}
}
} else {
variables.add(new CrySLObject(UNDERSCORE, NULL));
}
}
}
return new CrySLPredicate(null, innerPred.getPred().getPredName(), variables, (innerPred.getNot() != null ? true : false), conditional);
}
private ISLConstraint getPredicate(Pred pred) {
final List<ICrySLPredicateParameter> variables = new ArrayList<>();
if (pred.getParList() != null) {
for (final SuPar var : pred.getParList().getParameters()) {
if (var.getVal() != null) {
final LiteralExpression lit = var.getVal();
final ObjectImpl object = (ObjectImpl) ((LiteralExpression) lit.getLit().getName()).getValue();
final String type = ((ObjectDecl) object.eContainer()).getObjectType().getQualifiedName();
final String variable = object.getName();
final String part = var.getVal().getPart();
if (part != null) {
variables.add(new CrySLObject(variable, type, new CrySLSplitter(Integer.parseInt(lit.getInd()), filterQuotes(lit.getSplit()))));
} else {
final String consPred = var.getVal().getConsPred();
int ind;
if (consPred != null) {
if (consPred.equals("alg(")) {
ind = 0;
variables.add(new CrySLObject(variable, type, new CrySLSplitter(ind, filterQuotes("/"))));
} else if (consPred.equals("mode(")) {
ind = 1;
variables.add(new CrySLObject(variable, type, new CrySLSplitter(ind, filterQuotes("/"))));
} else if (consPred.equals("pad(")) {
ind = 2;
variables.add(new CrySLObject(variable, type, new CrySLSplitter(ind, filterQuotes("/"))));
}
} else {
variables.add(new CrySLObject(variable, type));
}
}
} else {
variables.add(new CrySLObject(UNDERSCORE, NULL));
}
}
}
return new CrySLPredicate(null, pred.getPredName(), variables, (((PredLit)pred.eContainer()).getNot() != null ? true : false), null);
}
private String getValueOfLiteral(final EObject name) {
String value = "";
if (name instanceof LiteralExpression) {
final SuperType preValue = ((LiteralExpression) name).getValue();
if (preValue != null) {
value = preValue.getName();
} else {
final EObject cons = ((LiteralExpression) name).getCons();
if (cons instanceof LiteralExpression) {
value = getValueOfLiteral(((LiteralExpression) cons).getName());
} else {
value = "";
}
}
} else {
value = ((Literal) name).getVal();
}
return filterQuotes(value);
}
private String getTypeName(final Constraint constraint, final String value) {
String typeName = "";
try {
Integer.parseInt(value);
typeName = "int";
} catch (NumberFormatException ex) {
typeName = ((ObjectDecl) ((LiteralExpression) ((LiteralExpression) ((LiteralExpression) constraint).getCons()).getName()).getValue().eContainer()).getObjectType()
.getQualifiedName();
}
return typeName;
}
private static String filterQuotes(final String dirty) {
return CharMatcher.anyOf("\"").removeFrom(dirty);
}
}
| 33,804 | 40.580566 | 197 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/cryslhandler/CryslReaderUtils.java | package crypto.cryslhandler;
import java.util.AbstractMap.SimpleEntry;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import crypto.rules.CrySLMethod;
import crypto.rules.CrySLRule;
import de.darmstadt.tu.crossing.crySL.Aggregate;
import de.darmstadt.tu.crossing.crySL.Event;
import de.darmstadt.tu.crossing.crySL.Method;
import de.darmstadt.tu.crossing.crySL.ObjectDecl;
import de.darmstadt.tu.crossing.crySL.Par;
import de.darmstadt.tu.crossing.crySL.ParList;
import de.darmstadt.tu.crossing.crySL.SuperType;
public class CryslReaderUtils {
public static final String outerFileSeparator = System.getProperty("file.separator");
public static final String innerFileSeparator = "/";
protected static List<CrySLMethod> resolveAggregateToMethodeNames(final Event leaf) {
if (leaf instanceof Aggregate) {
final Aggregate ev = (Aggregate) leaf;
return dealWithAggregate(ev);
} else {
final ArrayList<CrySLMethod> statements = new ArrayList<>();
CrySLMethod stringifyMethodSignature = stringifyMethodSignature(leaf);
if (stringifyMethodSignature != null) {
statements.add(stringifyMethodSignature);
}
return statements;
}
}
protected static List<CrySLMethod> dealWithAggregate(final Aggregate ev) {
final List<CrySLMethod> statements = new ArrayList<>();
for (final Event lab : ev.getLab()) {
if (lab instanceof Aggregate) {
statements.addAll(dealWithAggregate((Aggregate) lab));
} else {
statements.add(stringifyMethodSignature(lab));
}
}
return statements;
}
protected static CrySLMethod stringifyMethodSignature(final Event lab) {
if (!(lab instanceof SuperType)) {
return null;
}
final Method method = ((SuperType) lab).getMeth();
String methodName = method.getMethName().getSimpleName();
if (methodName == null) {
methodName = ((de.darmstadt.tu.crossing.crySL.Domainmodel) (method.eContainer().eContainer().eContainer())).getJavaType().getSimpleName();
}
final String qualifiedName =
((de.darmstadt.tu.crossing.crySL.Domainmodel) (method.eContainer().eContainer().eContainer())).getJavaType().getQualifiedName() + "." + methodName; // method.getMethName().getQualifiedName();
// qualifiedName = removeSPI(qualifiedName);
final List<Entry<String, String>> pars = new ArrayList<>();
final de.darmstadt.tu.crossing.crySL.Object returnValue = method.getLeftSide();
Entry<String, String> returnObject = null;
if (returnValue != null && returnValue.getName() != null) {
final ObjectDecl v = ((ObjectDecl) returnValue.eContainer());
returnObject = new SimpleEntry<>(returnValue.getName(), v.getObjectType().getQualifiedName() + ((v.getArray() != null) ? v.getArray() : ""));
} else {
returnObject = new SimpleEntry<>("_", "void");
}
final ParList parList = method.getParList();
if (parList != null) {
for (final Par par : parList.getParameters()) {
String parValue = "_";
if (par.getVal() != null && par.getVal().getName() != null) {
final ObjectDecl objectDecl = (ObjectDecl) par.getVal().eContainer();
parValue = par.getVal().getName();
final String parType = objectDecl.getObjectType().getIdentifier() + ((objectDecl.getArray() != null) ? objectDecl.getArray() : "");
pars.add(new SimpleEntry<>(parValue, parType));
} else {
pars.add(new SimpleEntry<>(parValue, "AnyType"));
}
}
}
return new CrySLMethod(qualifiedName, pars, new ArrayList<Boolean>(), returnObject);
}
public static File getResourceFromWithin(final String inputPath) {
return new File(inputPath);
}
}
| 3,691 | 38.276596 | 195 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/cryslhandler/StateMachineGraphBuilder.java | package crypto.cryslhandler;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import crypto.exceptions.CryptoAnalysisParserException;
import crypto.rules.CrySLMethod;
import crypto.rules.StateMachineGraph;
import crypto.rules.StateNode;
import crypto.rules.TransitionEdge;
import de.darmstadt.tu.crossing.crySL.Event;
import de.darmstadt.tu.crossing.crySL.Expression;
import de.darmstadt.tu.crossing.crySL.RequiredBlock;
/**
* This class will build a {@FiniteStateMachine} for a given ORDER expression from crysl rules.
* @author marvinvogel
*
*/
public class StateMachineGraphBuilder {
private final Expression order;
private final StateMachineGraph result;
private final Set<CrySLMethod> allMethods;
public StateMachineGraphBuilder(final Expression order, final RequiredBlock events) {
this.order = order;
this.allMethods = retrieveAllMethodsFromEVENTSBlock(events);
this.result = new StateMachineGraph();
}
private Set<CrySLMethod> retrieveAllMethodsFromEVENTSBlock(RequiredBlock events){
return events.getReq_event().parallelStream().flatMap(event -> CryslReaderUtils.resolveAggregateToMethodeNames(event).stream()).collect(Collectors.toSet());
}
/**
* This method will build the state machine. It is called recursively.
* For a collection of start nodes, which must already be added to the @attr result (the StateMachineGraph),
* it will append nodes and edges to result according to the given order and return all accepting end nodes.
*
* @param order the order expression from crysl.
* @param startNodes nodes from which the order can start.
* @param ignoreElementOp if true, it will ignore elementop (elementop=('+' | '?' | '*')). Default is false.
* @return all accepting nodes, according to the order
*/
private Set<StateNode> parseOrderAndGetEndStates(Expression order, Collection<StateNode> startNodes) {
/* Having a look at the Crysl Xtext definition for the Order section, we have
* -----------
*
* Order returns Expression:
* SimpleOrder ({Order.left=current} orderop=',' right=SimpleOrder)* | '*';
*
* SimpleOrder returns Expression:
* Primary ({SimpleOrder.left=current} orderop='|' right=Primary)*;
*
* Primary returns Expression:
* (orderEv+=[Event] elementop=('+' | '?' | '*')?) | ('(' Order ')' elementop=('+' | '?' | '*')?);
*
* -----------
* Based on this definition, the method will parse the Order section.
* In detail, we seperate Order, SimpleOrder and orderEv from elementop.
* To simplify this documentation, we create a synonym "ROOTS" for Order, SimpleOrder and orderEv.
* As you see in the definition the elementop can only be defined for any ROOT.
* Further, the recursion happens within ROOT elements.
* With this method, we will recursively get all end nodes for a given set of start nodes for one ROOT.
* After retrieving all end nodes, it then applies the logic of the element operator.
* In detail:
*
* Given start nodes, we fist append ROOT's nodes and edges according to the order and will retrieve it's end nodes.
* Therefore, we have three cases:
* (Event): Event should be the next transition in graph.
* We add edges from each start to a new node with Event as label.
* The new node is our end node.
* (,): Left side should be called before right side.
* We recursively call this method with order.leftSide and retrieve end nodes.
* We recursively call this method with order.rightSide use the end nodes from order.leftSide as start nodes.
* We retrieve our final end nodes from the call with order.rightSide.
* (|): Left side or right side should be called.
* We recursively call this method with order.leftSide and order.rightSide, with same start nodes.
* We retrieve our final end nodes by joining both return collections.
* To minimize the number of nodes, we aggregate all end nodes without outgoing edges to one node.
*
* Having start and end nodes, we can then modify the graph such that it applies the elementop.
* Therefore, we have three cases:
* ()+: We have to create a loop, according the path in order on the end node.
* We calculate all new edges generated on the start nodes.
* These edges where generated according to the current order.
* We simply create new edges from each end node to each target nodes of these edges.
* ()?: All start nodes are also end nodes.
* ()*: This is simply considered as (()+)?
*/
// store outgoing edges from one start node, to be able to calculate new created outgoing edges after the recursive call.
StateNode oneStartNode = startNodes.iterator().next();
Set<TransitionEdge> initialEdgesOnOneStartNode = this.result.getAllOutgoingEdges(oneStartNode);
final Set<StateNode> endNodes = Sets.newHashSet();
// first create nodes end edges according to ROOT's
if(order.getOrderop() == null) {
// This must be of type Primary
// That is actually the end of recursion or the deepest level.
StateNode endNode = this.result.createNewNode();
endNodes.add(endNode);
final List<CrySLMethod> label;
if(!order.getOrderEv().isEmpty()) {
// Event as label
label = CryslReaderUtils.resolveAggregateToMethodeNames(order.getOrderEv().get(0));
} else {
// this corresponds to '*' in Order
// any method is allowed to call
label = Lists.newArrayList(allMethods);
}
// add edges from each start node to the new end node
for(StateNode startNode: startNodes) {
this.result.createNewEdge(label, startNode, endNode);
}
} else if(order.getOrderop().equals(",")) {
// This must be of type Order
endNodes.addAll(parseOrderAndGetEndStates(order.getRight(), parseOrderAndGetEndStates(order.getLeft(), startNodes)));
} else if(order.getOrderop().equals("|")) {
// This must by of type SimpleOrder
endNodes.addAll(parseOrderAndGetEndStates(order.getLeft(), startNodes));
endNodes.addAll(parseOrderAndGetEndStates(order.getRight(), startNodes));
// reduce all end nodes without outgoing edges to one end node
Set<StateNode> endNodesWithOutgoingEdges = this.result.getEdges().parallelStream().map(edge -> edge.from()).filter(node -> endNodes.contains(node)).collect(Collectors.toSet());
if(endNodesWithOutgoingEdges.size() < endNodes.size()-1) {
endNodes.removeAll(endNodesWithOutgoingEdges);
StateNode aggrNode = this.result.aggregateNodesToOneNode(endNodes, endNodes.iterator().next());
endNodes.clear();
endNodes.add(aggrNode);
endNodes.addAll(endNodesWithOutgoingEdges);
}
}
// modify graph such that it applies elementop.
String elementop = order.getElementop();
if(elementop != null) {
if(!elementop.equals("?")) {
// elementop is "+" or "*"
Set<TransitionEdge> newOutgoingEdgesOnStartNodes = this.result.getAllOutgoingEdges(oneStartNode);
newOutgoingEdgesOnStartNodes.removeAll(initialEdgesOnOneStartNode);
for(TransitionEdge newEdge: newOutgoingEdgesOnStartNodes) {
endNodes.forEach(endNode -> this.result.createNewEdge(newEdge.getLabel(), endNode, newEdge.getRight()));
}
}
if(!elementop.equals("+")) {
// elementop is "?" or "*"
endNodes.addAll(startNodes);
}
}
return endNodes;
}
public StateMachineGraph buildSMG() {
StateNode initialNode = new StateNode("-1", true, true);
this.result.addNode(initialNode);
if (this.order != null) {
Set<StateNode> acceptingNodes = parseOrderAndGetEndStates(this.order, Sets.newHashSet(this.result.getNodes()));
acceptingNodes.parallelStream().forEach(node -> node.setAccepting(true));
}
if(this.result.getAllTransitions().isEmpty()) {
// to have an initial transition
this.result.createNewEdge(Lists.newArrayList(), initialNode, initialNode);
}
return this.result;
}
} | 8,031 | 45.16092 | 179 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/exceptions/CryptoAnalysisException.java | package crypto.exceptions;
/**
* This is an exception that is thrown when something is not working as expected and is explicitly related
* to the CryptoAnalysis tool.
*
*/
public class CryptoAnalysisException extends Exception {
private static final long serialVersionUID = -4977113204413613078L;
/**
* Constructs a new exception with the specified detail message.
*
* @param message a detail message.
*/
public CryptoAnalysisException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message a detail message.
* @param cause the cause of the exception.
*/
public CryptoAnalysisException(String message, Throwable cause) {
super(message, cause);
}
}
| 776 | 24.064516 | 106 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/exceptions/CryptoAnalysisParserException.java | package crypto.exceptions;
public class CryptoAnalysisParserException extends CryptoAnalysisException {
private static final long serialVersionUID = 5931419586323153592L;
/**
* Constructs a new exception with the specified detail message.
*
* @param message a detail message.
*/
public CryptoAnalysisParserException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message a detail message.
* @param cause the cause of the exception.
*/
public CryptoAnalysisParserException(String message, Throwable cause) {
super(message, cause);
}
}
| 649 | 23.074074 | 76 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/extractparameter/CallSiteWithExtractedValue.java | package crypto.extractparameter;
import crypto.reporting.SARIFReporter;
import crypto.rules.CrySLRule;
import soot.Value;
import soot.jimple.Constant;
/**
* Creates {@link CallSiteWithExtractedValue} a constructor with CallSiteWithParamIndex and ExtractedValue as parameter
*
* CallSiteWithParamIndex gives position of the location index of the error
* ExtractedValue gives the value of the call site
*/
public class CallSiteWithExtractedValue {
private CallSiteWithParamIndex cs;
private ExtractedValue val;
public CallSiteWithExtractedValue(CallSiteWithParamIndex cs, ExtractedValue val){
this.cs = cs;
this.val = val;
}
public CallSiteWithParamIndex getCallSite() {
return cs;
}
public ExtractedValue getVal() {
return val;
}
@Override
public String toString() {
String res = "";
switch(cs.getIndex()) {
case 0:
res = "First ";
break;
case 1:
res = "Second ";
break;
case 2:
res = "Third ";
break;
case 3:
res = "Fourth ";
break;
case 4:
res = "Fiveth ";
break;
case 5:
res = "Sixth ";
break;
}
res += "parameter";
if(val != null && val.getValue() != null){
Value allocVal = val.getValue();
if(allocVal instanceof Constant){
res += " (with value " + allocVal +")";
}
}
return res;
}
}
| 1,321 | 19.338462 | 119 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/extractparameter/CallSiteWithParamIndex.java | package crypto.extractparameter;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
public class CallSiteWithParamIndex{
private String varName;
/**
* @return the varName
*/
public String getVarName() {
return varName;
}
private int index;
private Val fact;
private Statement statement;
public CallSiteWithParamIndex(Statement u, Val fact, int index, String varName) {
this.fact = fact;
this.index = index;
this.varName = varName;
this.statement = u;
}
public int getIndex() {
return index;
}
@Override
public String toString() {
return varName +" at " +stmt() + " and " +index;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + index;
result = prime * result + ((statement == null) ? 0 : statement.hashCode());
result = prime * result + ((varName == null) ? 0 : varName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CallSiteWithParamIndex other = (CallSiteWithParamIndex) obj;
if (index != other.index)
return false;
if (statement == null) {
if (other.statement != null)
return false;
} else if (!statement.equals(other.statement))
return false;
if (varName == null) {
if (other.varName != null)
return false;
} else if (!varName.equals(other.varName))
return false;
return true;
}
public Val fact() {
return fact;
}
public Statement stmt() {
return statement;
}
}
| 1,597 | 18.487805 | 82 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/extractparameter/ExtractParameterAnalysis.java | package crypto.extractparameter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import boomerang.BackwardQuery;
import boomerang.Boomerang;
import boomerang.ForwardQuery;
import boomerang.callgraph.ObservableICFG;
import boomerang.jimple.AllocVal;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.BackwardBoomerangResults;
import crypto.analysis.CryptoScanner;
import crypto.boomerang.CogniCryptIntAndStringBoomerangOptions;
import crypto.rules.CrySLMethod;
import crypto.typestate.CrySLMethodToSootMethod;
import crypto.typestate.LabeledMatcherTransition;
import crypto.typestate.SootBasedStateMachineGraph;
import heros.utilities.DefaultValueMap;
import soot.Local;
import soot.Scene;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.Stmt;
import sync.pds.solver.nodes.Node;
import typestate.finiteautomata.MatcherTransition;
import wpds.impl.Weight.NoWeight;
public class ExtractParameterAnalysis {
private Map<Statement,SootMethod> allCallsOnObject;
private Collection<LabeledMatcherTransition> events = Sets.newHashSet();
private CryptoScanner cryptoScanner;
private Multimap<CallSiteWithParamIndex, ExtractedValue> collectedValues = HashMultimap.create();
private Collection<CallSiteWithParamIndex> querySites = Sets.newHashSet();
private Multimap<CallSiteWithParamIndex, Type> propagatedTypes = HashMultimap.create();
private DefaultValueMap<AdditionalBoomerangQuery, AdditionalBoomerangQuery> additionalBoomerangQuery = new DefaultValueMap<AdditionalBoomerangQuery, AdditionalBoomerangQuery>() {
@Override
protected AdditionalBoomerangQuery createItem(AdditionalBoomerangQuery key) {
return key;
}
};
public ExtractParameterAnalysis(CryptoScanner cryptoScanner, Map<Statement, SootMethod> allCallsOnObject, SootBasedStateMachineGraph fsm) {
this.cryptoScanner = cryptoScanner;
this.allCallsOnObject = allCallsOnObject;
for(MatcherTransition m : fsm.getAllTransitions()) {
if(m instanceof LabeledMatcherTransition) {
this.events.add((LabeledMatcherTransition) m );
}
}
}
public void run() {
for(Entry<Statement, SootMethod> callSiteWithCallee : allCallsOnObject.entrySet()) {
Statement callSite = callSiteWithCallee.getKey();
SootMethod declaredCallee = callSiteWithCallee.getValue();
if(callSite.isCallsite()){
for(LabeledMatcherTransition e : events) {
if(e.matches(declaredCallee)) {
injectQueryAtCallSite(e.label(),callSite);
}
}
}
}
for (AdditionalBoomerangQuery q : additionalBoomerangQuery.keySet()) {
q.solve();
}
}
public Multimap<CallSiteWithParamIndex, ExtractedValue> getCollectedValues() {
return collectedValues;
}
public Multimap<CallSiteWithParamIndex, Type> getPropagatedTypes() {
return propagatedTypes;
}
public Collection<CallSiteWithParamIndex> getAllQuerySites() {
return querySites;
}
private void injectQueryAtCallSite(List<CrySLMethod> list, Statement callSite) {
if(!callSite.isCallsite())
return;
for(CrySLMethod matchingDescriptor : list){
for(SootMethod m : CrySLMethodToSootMethod.v().convert(matchingDescriptor)){
SootMethod method = callSite.getUnit().get().getInvokeExpr().getMethod();
if (!m.equals(method))
continue;
{
int index = 0;
for(Entry<String, String> param : matchingDescriptor.getParameters()){
if(!param.getKey().equals("_")){
soot.Type parameterType = method.getParameterType(index);
if(parameterType.toString().equals(param.getValue())){
addQueryAtCallsite(param.getKey(), callSite, index);
}
}
index++;
}
}
}
}
}
public void addQueryAtCallsite(final String varNameInSpecification, final Statement stmt, final int index) {
if(!stmt.isCallsite())
return;
Value parameter = stmt.getUnit().get().getInvokeExpr().getArg(index);
if (!(parameter instanceof Local)) {
Val parameterVal = new Val(parameter, stmt.getMethod());
CallSiteWithParamIndex cs = new CallSiteWithParamIndex(stmt, parameterVal, index, varNameInSpecification);
Set<Node<Statement,Val>> dataFlowPath = Sets.newHashSet();
dataFlowPath.add(new Node<Statement, Val>(stmt, parameterVal));
collectedValues.put(cs
, new ExtractedValue(stmt,parameter, dataFlowPath));
querySites.add(cs);
return;
}
Val queryVal = new Val((Local) parameter, stmt.getMethod());
for(Unit pred : cryptoScanner.icfg().getPredsOf(stmt.getUnit().get())) {
AdditionalBoomerangQuery query = additionalBoomerangQuery
.getOrCreate(new AdditionalBoomerangQuery(new Statement((Stmt)pred, stmt.getMethod()), queryVal));
CallSiteWithParamIndex callSiteWithParamIndex = new CallSiteWithParamIndex(stmt, queryVal, index, varNameInSpecification);
querySites.add(callSiteWithParamIndex);
query.addListener(new QueryListener() {
@Override
public void solved(AdditionalBoomerangQuery q, BackwardBoomerangResults<NoWeight> res) {
propagatedTypes.putAll(callSiteWithParamIndex, res.getPropagationType());
for (ForwardQuery v : res.getAllocationSites().keySet()) {
ExtractedValue extractedValue = null;
if(v.var() instanceof AllocVal) {
AllocVal allocVal = (AllocVal) v.var();
extractedValue = new ExtractedValue(allocVal.allocationStatement(),allocVal.allocationValue(), res.getDataFlowPath(v));
} else {
extractedValue = new ExtractedValue(v.stmt(),v.var().value(), res.getDataFlowPath(v));
}
collectedValues.put(callSiteWithParamIndex,
extractedValue);
//Special handling for toCharArray method (required for NeverTypeOf constraint)
if(v.stmt().isCallsite()) {
String calledMethodSignature = v.stmt().getUnit().get().getInvokeExpr().getMethod().getSignature();
if(calledMethodSignature.equals("<java.lang.String: char[] toCharArray()>")){
propagatedTypes.put(callSiteWithParamIndex, Scene.v().getType("java.lang.String"));
}
}
}
}
});
}
}
public void addAdditionalBoomerangQuery(AdditionalBoomerangQuery q, QueryListener listener) {
AdditionalBoomerangQuery query = additionalBoomerangQuery.getOrCreate(q);
query.addListener(listener);
}
public class AdditionalBoomerangQuery extends BackwardQuery {
public AdditionalBoomerangQuery(Statement stmt, Val variable) {
super(stmt, variable);
}
protected boolean solved;
private List<QueryListener> listeners = Lists.newLinkedList();
private BackwardBoomerangResults<NoWeight> res;
public void solve() {
Boomerang boomerang = new Boomerang(new CogniCryptIntAndStringBoomerangOptions()) {
@Override
public ObservableICFG<Unit, SootMethod> icfg() {
return ExtractParameterAnalysis.this.cryptoScanner.icfg();
}
};
res = boomerang.solve(this);
for (QueryListener l : Lists.newLinkedList(listeners)) {
l.solved(this, res);
}
solved = true;
}
public void addListener(QueryListener q) {
if (solved) {
q.solved(this, res);
return;
}
listeners.add(q);
}
}
private static interface QueryListener {
public void solved(AdditionalBoomerangQuery q, BackwardBoomerangResults<NoWeight> res);
}
}
| 7,446 | 34.293839 | 179 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/extractparameter/ExtractedValue.java | package crypto.extractparameter;
import java.util.Set;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import soot.Value;
import sync.pds.solver.nodes.Node;
public class ExtractedValue {
private Statement stmt;
private Value val;
private Set<Node<Statement, Val>> dataFlowPath;
public ExtractedValue(Statement stmt, Value val, Set<Node<Statement, Val>> dataFlowPath) {
this.stmt = stmt;
this.val = val;
this.dataFlowPath = dataFlowPath;
}
public Statement stmt() {
return stmt;
}
public Value getValue() {
return val;
}
@Override
public String toString() {
return "Extracted Value: " + val + " at " +stmt;
}
public Set<Node<Statement, Val>> getDataFlowPath() {
return dataFlowPath;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((stmt == null) ? 0 : stmt.hashCode());
result = prime * result + ((val == null) ? 0 : val.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ExtractedValue other = (ExtractedValue) obj;
if (stmt == null) {
if (other.stmt != null)
return false;
} else if (!stmt.equals(other.stmt))
return false;
if (val == null) {
if (other.val != null)
return false;
} else if (!val.equals(other.val))
return false;
return true;
}
}
| 1,456 | 19.814286 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/interfaces/FiniteStateMachine.java | package crypto.interfaces;
import java.util.Collection;
public interface FiniteStateMachine<State> {
Transition<State> getInitialTransition();
Collection<State> getAcceptingStates();
Collection<? extends Transition<State>> getAllTransitions();
}
| 254 | 20.25 | 61 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/interfaces/ICrySLPredicateParameter.java | package crypto.interfaces;
import java.io.Serializable;
public interface ICrySLPredicateParameter extends Serializable {
public String getName();
}
| 154 | 14.5 | 64 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/interfaces/ISLConstraint.java | package crypto.interfaces;
import java.util.Set;
import boomerang.jimple.Statement;
public interface ISLConstraint extends java.io.Serializable, ICrySLPredicateParameter {
public Set<String> getInvolvedVarNames();
public void setLocation(Statement location);
public Statement getLocation();
}
| 304 | 18.0625 | 87 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/interfaces/Transition.java | package crypto.interfaces;
import java.util.List;
import crypto.rules.CrySLMethod;
public interface Transition<State>{
State from();
State to();
List<CrySLMethod> getLabel();
} | 182 | 15.636364 | 35 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/preanalysis/SeedFactory.java | package crypto.preanalysis;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import boomerang.Query;
import boomerang.WeightedForwardQuery;
import crypto.rules.CrySLRule;
import crypto.typestate.FiniteStateMachineToTypestateChangeFunction;
import crypto.typestate.SootBasedStateMachineGraph;
import soot.SootMethod;
import soot.Unit;
import typestate.TransitionFunction;
public class SeedFactory {
private List<FiniteStateMachineToTypestateChangeFunction> idealAnalysisDefs = Lists.newLinkedList();
private Set<Query> seeds = Sets.newHashSet();
public SeedFactory(List<CrySLRule> rules) {
for(CrySLRule rule : rules){
idealAnalysisDefs.add(new FiniteStateMachineToTypestateChangeFunction(new SootBasedStateMachineGraph(rule.getUsagePattern())));
}
}
public void generate(SootMethod method, Unit unit) {
for(FiniteStateMachineToTypestateChangeFunction defs : idealAnalysisDefs){
Collection<WeightedForwardQuery<TransitionFunction>> found = defs.generateSeed(method, unit);
seeds.addAll(found);
}
}
public boolean hasSeeds(){
return !seeds.isEmpty();
}
}
| 1,193 | 28.121951 | 130 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/predicates/PredicateHandler.java | package crypto.predicates;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.ForwardBoomerangResults;
import crypto.analysis.AlternativeReqPredicate;
import crypto.analysis.AnalysisSeedWithSpecification;
import crypto.analysis.ClassSpecification;
import crypto.analysis.CryptoScanner;
import crypto.analysis.EnsuredCrySLPredicate;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.RequiredCrySLPredicate;
import crypto.analysis.ResultsHandler;
import crypto.analysis.errors.PredicateContradictionError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.extractparameter.CallSiteWithExtractedValue;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLConstraint;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLRule;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import typestate.TransitionFunction;
public class PredicateHandler {
private final class AddPredicateToOtherSeed implements ResultsHandler {
private final Statement statement;
private final Value base;
private final SootMethod callerMethod;
private final EnsuredCrySLPredicate ensPred;
private final AnalysisSeedWithSpecification secondSeed;
private AddPredicateToOtherSeed(Statement statement, Value base, SootMethod callerMethod, EnsuredCrySLPredicate ensPred, AnalysisSeedWithSpecification secondSeed) {
this.statement = statement;
this.base = base;
this.callerMethod = callerMethod;
this.ensPred = ensPred;
this.secondSeed = secondSeed;
}
@Override
public void done(ForwardBoomerangResults<TransitionFunction> results) {
if (results.asStatementValWeightTable().row(statement).containsKey(new Val(base, callerMethod))) {
secondSeed.addEnsuredPredicate(ensPred);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + ((callerMethod == null) ? 0 : callerMethod.hashCode());
result = prime * result + ((ensPred == null) ? 0 : ensPred.hashCode());
result = prime * result + ((secondSeed == null) ? 0 : secondSeed.hashCode());
result = prime * result + ((statement == null) ? 0 : statement.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AddPredicateToOtherSeed other = (AddPredicateToOtherSeed) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (base == null) {
if (other.base != null)
return false;
} else if (!base.equals(other.base))
return false;
if (callerMethod == null) {
if (other.callerMethod != null)
return false;
} else if (!callerMethod.equals(other.callerMethod))
return false;
if (ensPred == null) {
if (other.ensPred != null)
return false;
} else if (!ensPred.equals(other.ensPred))
return false;
if (secondSeed == null) {
if (other.secondSeed != null)
return false;
} else if (!secondSeed.equals(other.secondSeed))
return false;
if (statement == null) {
if (other.statement != null)
return false;
} else if (!statement.equals(other.statement))
return false;
return true;
}
private PredicateHandler getOuterType() {
return PredicateHandler.this;
}
}
private final Table<Statement, Val, Set<EnsuredCrySLPredicate>> existingPredicates = HashBasedTable.create();
private final Table<Statement, IAnalysisSeed, Set<EnsuredCrySLPredicate>> existingPredicatesObjectBased = HashBasedTable.create();
private final Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> expectedPredicateObjectBased = HashBasedTable.create();
private final CryptoScanner cryptoScanner;
public PredicateHandler(CryptoScanner cryptoScanner) {
this.cryptoScanner = cryptoScanner;
}
public boolean addNewPred(IAnalysisSeed seedObj, Statement statement, Val variable, EnsuredCrySLPredicate ensPred) {
Set<EnsuredCrySLPredicate> set = getExistingPredicates(statement, variable);
boolean added = set.add(ensPred);
assert existingPredicates.get(statement, variable).contains(ensPred);
if (added) {
onPredicateAdded(seedObj, statement, variable, ensPred);
}
cryptoScanner.getAnalysisListener().onSecureObjectFound(seedObj);
Set<EnsuredCrySLPredicate> predsObjBased = existingPredicatesObjectBased.get(statement, seedObj);
if (predsObjBased == null)
predsObjBased = Sets.newHashSet();
predsObjBased.add(ensPred);
existingPredicatesObjectBased.put(statement, seedObj, predsObjBased);
return added;
}
/**
* @return the existingPredicates
*/
public Set<EnsuredCrySLPredicate> getExistingPredicates(Statement stmt, Val seed) {
Set<EnsuredCrySLPredicate> set = existingPredicates.get(stmt, seed);
if (set == null) {
set = Sets.newHashSet();
existingPredicates.put(stmt, seed, set);
}
return set;
}
private void onPredicateAdded(IAnalysisSeed seedObj, Statement statement, Val seed, EnsuredCrySLPredicate ensPred) {
if (statement.isCallsite()) {
InvokeExpr ivexpr = ((Stmt) statement.getUnit().get()).getInvokeExpr();
if (ivexpr instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ivexpr;
SootMethod method = iie.getMethod();
SootMethod callerMethod = statement.getMethod();
Value base = iie.getBase();
boolean paramMatch = false;
for (Value arg : iie.getArgs()) {
if (seed.value() != null && seed.value().equals(arg))
paramMatch = true;
}
if (paramMatch) {
for (AnalysisSeedWithSpecification secondSeed : Lists.newArrayList(cryptoScanner.getAnalysisSeeds())) {
secondSeed.registerResultsHandler(new AddPredicateToOtherSeed(statement, base, callerMethod, ensPred, secondSeed));
}
}
}
if (ivexpr instanceof StaticInvokeExpr && statement.getUnit().get() instanceof AssignStmt) {
StaticInvokeExpr iie = (StaticInvokeExpr) ivexpr;
boolean paramMatch = false;
for (Value arg : iie.getArgs()) {
if (seed.value() != null && seed.value().equals(arg))
paramMatch = true;
}
if (paramMatch) {
for (AnalysisSeedWithSpecification spec : Lists.newArrayList(cryptoScanner.getAnalysisSeeds())) {
if (spec.stmt().equals(statement)) {
spec.addEnsuredPredicate(ensPred);
}
}
}
}
}
}
public void expectPredicate(IAnalysisSeed object, Statement stmt, CrySLPredicate predToBeEnsured) {
for (Unit succ : cryptoScanner.icfg().getSuccsOf(stmt.getUnit().get())) {
Set<CrySLPredicate> set = expectedPredicateObjectBased.get(succ, object);
if (set == null)
set = Sets.newHashSet();
set.add(predToBeEnsured);
expectedPredicateObjectBased.put(new Statement((Stmt) succ, stmt.getMethod()), object, set);
}
}
public void checkPredicates() {
checkMissingRequiredPredicates();
checkForContradictions();
cryptoScanner.getAnalysisListener().ensuredPredicates(this.existingPredicates, expectedPredicateObjectBased, computeMissingPredicates());
}
private void checkMissingRequiredPredicates() {
for (AnalysisSeedWithSpecification seed : cryptoScanner.getAnalysisSeeds()) {
Set<ISLConstraint> missingPredicates = seed.getMissingPredicates();
for (ISLConstraint pred : missingPredicates) {
if (pred instanceof RequiredCrySLPredicate) {
reportMissingPred(seed, (RequiredCrySLPredicate) pred);
} else if (pred instanceof CrySLConstraint) {
for (CrySLPredicate altPred : ((AlternativeReqPredicate) pred).getAlternatives()) {
reportMissingPred(seed, new RequiredCrySLPredicate(altPred, altPred.getLocation()));
}
}
}
}
}
private void reportMissingPred(AnalysisSeedWithSpecification seed, RequiredCrySLPredicate missingPred) {
CrySLRule rule = seed.getSpec().getRule();
if (!rule.getPredicates().parallelStream().anyMatch(e -> missingPred.getPred().getPredName().equals(e.getPredName()) && missingPred.getPred().getParameters().get(0).equals(e.getParameters().get(0)))) {
for (CallSiteWithParamIndex v : seed.getParameterAnalysis().getAllQuerySites()) {
if (missingPred.getPred().getInvolvedVarNames().contains(v.getVarName()) && v.stmt().equals(missingPred.getLocation())) {
cryptoScanner.getAnalysisListener().reportError(seed,
new RequiredPredicateError(missingPred.getPred(), missingPred.getLocation(), seed.getSpec().getRule(), new CallSiteWithExtractedValue(v, null)));
}
}
}
}
private void checkForContradictions() {
Set<Entry<CrySLPredicate, CrySLPredicate>> contradictionPairs = new HashSet<Entry<CrySLPredicate, CrySLPredicate>>();
for (ClassSpecification c : cryptoScanner.getClassSpecifictions()) {
CrySLRule rule = c.getRule();
for (ISLConstraint cons : rule.getConstraints()) {
if (cons instanceof CrySLPredicate && ((CrySLPredicate) cons).isNegated()) {
contradictionPairs.add(new SimpleEntry<CrySLPredicate, CrySLPredicate>(rule.getPredicates().get(0), ((CrySLPredicate) cons).setNegated(false)));
}
}
}
for (Statement generatingPredicateStmt : expectedPredicateObjectBased.rowKeySet()) {
for (Entry<Val, Set<EnsuredCrySLPredicate>> exPredCell : existingPredicates.row(generatingPredicateStmt).entrySet()) {
Set<String> preds = new HashSet<String>();
for (EnsuredCrySLPredicate exPred : exPredCell.getValue()) {
preds.add(exPred.getPredicate().getPredName());
}
for (Entry<CrySLPredicate, CrySLPredicate> disPair : contradictionPairs) {
if (preds.contains(disPair.getKey().getPredName()) && preds.contains(disPair.getValue().getPredName())) {
cryptoScanner.getAnalysisListener().reportError(null, new PredicateContradictionError(generatingPredicateStmt, null, disPair));
}
}
}
}
}
private Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> computeMissingPredicates() {
Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> res = HashBasedTable.create();
for (Cell<Statement, IAnalysisSeed, Set<CrySLPredicate>> c : expectedPredicateObjectBased.cellSet()) {
Set<EnsuredCrySLPredicate> exPreds = existingPredicatesObjectBased.get(c.getRowKey(), c.getColumnKey());
if (c.getValue() == null)
continue;
HashSet<CrySLPredicate> expectedPreds = new HashSet<>(c.getValue());
if (exPreds == null) {
exPreds = Sets.newHashSet();
}
for (EnsuredCrySLPredicate p : exPreds) {
expectedPreds.remove(p.getPredicate());
}
if (!expectedPreds.isEmpty()) {
res.put(c.getRowKey(), c.getColumnKey(), expectedPreds);
}
}
return res;
}
}
| 11,228 | 37.854671 | 203 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/providerdetection/ProviderDetection.java | package crypto.providerdetection;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import boomerang.BackwardQuery;
import boomerang.Boomerang;
import boomerang.DefaultBoomerangOptions;
import boomerang.ForwardQuery;
import boomerang.callgraph.ObservableICFG;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.AbstractBoomerangResults;
import boomerang.results.BackwardBoomerangResults;
import boomerang.seedfactory.SeedFactory;
import crypto.exceptions.CryptoAnalysisException;
import crypto.rules.CrySLRule;
import crypto.rules.CrySLRuleReader;
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.Stmt;
import soot.jimple.TableSwitchStmt;
import soot.jimple.internal.JAssignStmt;
import soot.jimple.internal.JIfStmt;
import soot.jimple.internal.JStaticInvokeExpr;
import wpds.impl.Weight.NoWeight;
/**
* The ProviderDetection class helps in detecting the provider used when
* coding with JCA's Cryptographic APIs and chooses the corresponding set of
* CrySL rules that are implemented for that provider.
*
* @author Enri Ozuni
*
*/
public class ProviderDetection {
private static final Logger LOGGER = LoggerFactory.getLogger(ProviderDetection.class);
private String provider = null;
private String rulesDirectory = null;
private static final String BOUNCY_CASTLE = "BouncyCastle";
private static final String[] PROVIDER_VALUES = new String[] {"BC", "BCPQC", "BCJSSE"};
private static final Set<String> SUPPORTED_PROVIDERS = new HashSet<>(Arrays.asList(PROVIDER_VALUES));
/**
* Returns the detected provider.
*
*/
public String getProvider() {
return provider;
}
/**
* Returns the rules directory of the detected provider.
*
*/
public String getRulesDirectory() {
return rulesDirectory;
}
//This method is used for testing purposes.
protected void setRulesDirectory(String rulesDirectory) {
this.rulesDirectory = rulesDirectory;
}
/**
* This method does the Provider Detection analysis and returns the detected
* provider after the analysis is finished. If no Provider is detected,
* then it will return null value, meaning that there was no provider used.
*
* @param observableDynamicICFG
*
* @param rootRulesDirectory
*
*/
public String doAnalysis(ObservableICFG<Unit, SootMethod> observableDynamicICFG, String rootRulesDirectory) {
for(SootClass sootClass : Scene.v().getApplicationClasses()) {
for(SootMethod sootMethod : sootClass.getMethods()) {
if(sootMethod.hasActiveBody()) {
Body body = sootMethod.getActiveBody();
for (Unit unit : body.getUnits()) {
if(unit instanceof JAssignStmt) {
JAssignStmt statement = (JAssignStmt) unit;
Value rightSideOfStatement = statement.getRightOp();
if (rightSideOfStatement instanceof JStaticInvokeExpr) {
JStaticInvokeExpr expression = (JStaticInvokeExpr) rightSideOfStatement;
SootMethod method = expression.getMethod();
String methodName = method.getName();
SootClass declaringClass = method.getDeclaringClass();
String declaringClassName = declaringClass.toString();
declaringClassName = declaringClassName.substring(declaringClassName.lastIndexOf(".") + 1);
int methodParameterCount = method.getParameterCount();
if((methodName.matches("getInstance")) && (methodParameterCount==2) ) {
// Gets the second parameter from getInstance() method, since it is the provider parameter
Value providerValue = expression.getArg(1);
String providerType = getProviderType(providerValue);
if(providerType.matches("java.security.Provider")) {
this.provider = getProviderWhenTypeProvider(statement, sootMethod, providerValue, observableDynamicICFG);
if((this.provider != null) && (rulesExist(rootRulesDirectory+File.separator+this.provider))) {
this.rulesDirectory = rootRulesDirectory+File.separator+this.provider;
return this.provider;
}
}
else if (providerType.matches("java.lang.String")) {
if(SUPPORTED_PROVIDERS.contains(providerValue.toString().replaceAll("\"",""))) {
if(providerValue.toString().replaceAll("\"","").contains("BC")) {
return "BouncyCastle-JCA";
}
}
this.provider = getProviderWhenTypeString(providerValue, body);
// Gets the boolean value of whether the provider is passed
// using IF-ELSE, SWITCH statements or TERNARY operators
boolean ifStmt = checkIfStmt(providerValue, body);
boolean switchStmt = checkSwitchStmt(providerValue, body);
if((!ifStmt) && (!switchStmt) && (this.provider != null) && (rulesExist(rootRulesDirectory+File.separator+this.provider))) {
this.rulesDirectory = rootRulesDirectory+File.separator+this.provider;
return this.provider;
}
}
}
}
}
}
}
}
}
return this.provider;
}
/**
* This method returns the type of Provider detected, since
* it can be either `java.security.Provider` or `java.lang.String`.
*
* @param providerValue
*/
private String getProviderType(Value providerValue) {
String providerType = providerValue.getType().toString();
return providerType;
}
/**
* This method return the provider used when Provider detected is of type `java.security.Provider`.
*
* @param statement
*
* @param sootMethod
*
* @param providerValue
*
* @param icfg
*
*/
private String getProviderWhenTypeProvider(JAssignStmt statement, SootMethod sootMethod, Value providerValue, ObservableICFG<Unit, SootMethod> observableDynamicICFG) {
String provider = null;
//Create a Boomerang solver.
Boomerang solver = new Boomerang(new DefaultBoomerangOptions(){
public boolean onTheFlyCallGraph() {
//Must be turned of if no SeedFactory is specified.
return false;
};
}) {
@Override
public ObservableICFG<Unit, SootMethod> icfg() {
return observableDynamicICFG;
}
@Override
public SeedFactory<NoWeight> getSeedFactory() {
return null;
}
};
Map<ForwardQuery, AbstractBoomerangResults<NoWeight>.Context> map = Maps.newHashMap();
for(Unit pred : observableDynamicICFG.getPredsOf(statement)) {
//Create a backward query
BackwardQuery query = new BackwardQuery(new Statement((Stmt) pred,sootMethod), new Val(providerValue, sootMethod));
//Submit query to the solver.
BackwardBoomerangResults<NoWeight> backwardQueryResults = solver.solve(query);
map.putAll(backwardQueryResults.getAllocationSites());
}
// The Provider can be correctly detected from this static analysis, if there is only one allocation site
// where the Provider variable was initialized. Otherwise, it throws an error because it is not possible
// to detect for sure the provider, if is given as parameter to the getInstance() method through the use of
// IF-ELSE, SWITCH statements or TERNARY operators
if(map.size() == 1) {
for(Entry<ForwardQuery, AbstractBoomerangResults<NoWeight>.Context> entry : map.entrySet()) {
ForwardQuery forwardQuery = entry.getKey();
Val forwardQueryVal = forwardQuery.var();
Value value = forwardQueryVal.value();
Type valueType = value.getType();
String valueTypeString = valueType.toString();
// In here are listed all the supported providers so far
if(valueTypeString.contains(BOUNCY_CASTLE)) {
provider = "BouncyCastle-JCA";
}
}
}
else if (map.size() > 1) {
LOGGER.error("The provider parameter must be passed directly to the"
+ " getInstance() method call, and not through IF-ELSE, SWITCH statements or"
+ " TERNARY operators.");
}
else {
LOGGER.error("Error occured to detect provider in the Provider Detection"
+ " analysis.");
}
return provider;
}
/**
* This method return the provider used when Provider detected is of type `java.lang.String`.
*
* @param providerValue
*
* @param body
* - i.e. the ActiveBody
*
*/
private String getProviderWhenTypeString(Value providerValue, Body body) {
for(Unit unit : body.getUnits()) {
if(unit instanceof JAssignStmt) {
JAssignStmt assignStatement = (JAssignStmt) unit;
if(assignStatement.getLeftOp().equals(providerValue)) {
String provider = assignStatement.getRightOp().toString().replaceAll("\"","");
if(provider.equals("BC") || provider.equals("BCPQC") || provider.equals("BCJSSE")) {
provider = "BouncyCastle-JCA";
return provider;
}
}
}
}
return null;
}
/**
* This method checks if the provider detected has only one allocation site
* and it is not flowing through IF-ELSE statements or TERNARY operators, because
* otherwise the provider can not be correctly detected through the use of
* static analysis. In case it has more than one allocation site, this method
* return true.
*
* @param providerValue
*
* @param body
* - i.e. the ActiveBody
*
*/
private boolean checkIfStmt(Value providerValue, Body body) {
String value = providerValue.toString();
for(Unit unit : body.getUnits()) {
if(unit instanceof JIfStmt) {
JIfStmt ifStatement = (JIfStmt) unit;
if(ifStatement.toString().contains(value)) {
LOGGER.error("The provider parameter must be passed directly to the"
+ " getInstance() method call, and not through IF-ELSE statements or"
+ " TERNARY operators.");
return true;
}
}
}
return false;
}
/**
* This method checks if the provider detected has only one allocation site
* and it is not flowing through SWITCH statements, because otherwise the
* provider can not be correctly detected through the use of static analysis.
* In case it has more than one allocation site, this method return true.
*
* @param providerValue
*
* @param body
* - i.e. the ActiveBody
*
*/
private boolean checkSwitchStmt(Value providerValue, Body body) {
String value = providerValue.toString();
for(Unit unit : body.getUnits()) {
if(unit instanceof TableSwitchStmt) {
TableSwitchStmt switchStatement = (TableSwitchStmt) unit;
if(switchStatement.toString().contains(value)) {
LOGGER.error("The provider parameter must be passed directly to the"
+ " getInstance() method call, and not through SWITCH statements.");
return true;
}
}
}
return false;
}
/**
* This method is used to check if the CryptSL rules from the detected Provider do exist.
*
* @param providerRulesDirectory
*
*/
private boolean rulesExist(String providerRulesDirectory) {
File rulesDirectory = new File(providerRulesDirectory);
if(rulesDirectory.exists()) {
return true;
}
return false;
}
/**
* This method is used to choose the CryptSL rules in a directory from the detected provider and should
* be called after the `doAnalysis()` method.
*
* @param providerRulesDirectory
*
*/
public List<CrySLRule> chooseRules(String providerRulesDirectory) {
List<CrySLRule> rules = Lists.newArrayList();
this.rulesDirectory = providerRulesDirectory;
try {
rules.addAll(CrySLRuleReader.readFromDirectory(new File(providerRulesDirectory)));
} catch (CryptoAnalysisException e) {
LOGGER.error("Error happened when getting the CrySL rules from the "
+ "specified directory: "+providerRulesDirectory, e);
}
return rules;
}
/**
* This method is used to choose the CryptSL rules in a zip file from the detected provider and should
* be called after the `doAnalysis()` method.
*
* @param providerRulesZip
*
*/
public List<CrySLRule> chooseRulesZip(String providerRulesZip) {
List<CrySLRule> rules = Lists.newArrayList();
this.rulesDirectory = providerRulesZip;
try {
rules.addAll(CrySLRuleReader.readFromZipFile(new File(providerRulesZip)));
} catch (CryptoAnalysisException e) {
LOGGER.error("Error happened when getting the CrySL rules from the "
+ "specified zip file: "+providerRulesZip, e);
}
return rules;
}
}
| 12,731 | 32.505263 | 168 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/CSVReporter.java | package crypto.reporting;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import boomerang.BackwardQuery;
import boomerang.Query;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.ForwardBoomerangResults;
import crypto.analysis.AnalysisSeedWithSpecification;
import crypto.analysis.EnsuredCrySLPredicate;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.errors.AbstractError;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.ForbiddenMethodError;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.ImpreciseValueExtractionError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.NeverTypeOfError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.extractparameter.ExtractedValue;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLRule;
import soot.MethodOrMethodContext;
import soot.Scene;
import soot.SootMethod;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.util.queue.QueueReader;
import sync.pds.solver.nodes.Node;
import typestate.TransitionFunction;
public class CSVReporter extends ErrorMarkerListener {
private static final Logger LOGGER = LoggerFactory.getLogger(CSVReporter.class);
private static final String CSV_SEPARATOR = ";";
private Set<AbstractError> errors = Sets.newHashSet();
private int seeds;
private List<String> headers = Lists.newArrayList();
private Map<String,String> headersToValues = Maps.newHashMap();
private List<CrySLRule> rules;
private Set<SootMethod> dataflowReachableMethods = Sets.newHashSet();
private Stopwatch analysisTime = Stopwatch.createUnstarted();
/**
* Path of directory of analysis reports
*/
private File reportDir;
/**
* name of the analysis report
*/
private static final String REPORT_NAME = "CryptoAnalysis-Report.csv";
/**
* the headers of CSV report
*/
private enum Headers{
SoftwareID,SeedObjectCount,CallGraphTime_ms,CryptoAnalysisTime_ms,CallGraphReachableMethods,
CallGraphReachableMethods_ActiveBodies,DataflowVisitedMethod
}
/**
* Creates {@link CSVReporter} a constructor with reportDir, softwareId, rules and callGraphConstructionTime as parameter
*
* @param reportDir a {@link String} path giving the location of the report directory
* @param softwareId {@link Format} An identifier used to label output files in CSV report format
* @param rules {@link CrySLRule} the rules with which the project is analyzed
* @param callGraphConstructionTime {@link long} call graph construction time in ms
*/
public CSVReporter(String reportDir, String softwareId, List<CrySLRule> rules, long callGraphConstructionTime) {
this.reportDir = (reportDir != null ? new File(reportDir) : new File(System.getProperty("user.dir")));
this.rules = rules;
ReachableMethods reachableMethods = Scene.v().getReachableMethods();
QueueReader<MethodOrMethodContext> listener = reachableMethods.listener();
Set<SootMethod> visited = Sets.newHashSet();
int callgraphReachableMethodsWithActiveBodies = 0;
while (listener.hasNext()) {
MethodOrMethodContext next = listener.next();
visited.add(next.method());
if (next.method().hasActiveBody()) {
callgraphReachableMethodsWithActiveBodies++;
}
}
int callgraphReachableMethods = visited.size();
for(Headers h : Headers.values()){
headers.add(h.toString());
}
put(Headers.SoftwareID,softwareId);
put(Headers.CallGraphTime_ms,callGraphConstructionTime);
put(Headers.CallGraphReachableMethods,callgraphReachableMethods);
put(Headers.CallGraphReachableMethods_ActiveBodies,callgraphReachableMethodsWithActiveBodies);
addDynamicHeader(ConstraintError.class.getSimpleName());
addDynamicHeader(NeverTypeOfError.class.getSimpleName());
addDynamicHeader(HardCodedError.class.getSimpleName());
addDynamicHeader(TypestateError.class.getSimpleName());
addDynamicHeader(RequiredPredicateError.class.getSimpleName());
addDynamicHeader(IncompleteOperationError.class.getSimpleName());
addDynamicHeader(ImpreciseValueExtractionError.class.getSimpleName());
addDynamicHeader(ForbiddenMethodError.class.getSimpleName());
}
private void addDynamicHeader(String name) {
headers.add(name+"_sum");
for(CrySLRule r : rules){
headers.add(name+"_"+r.getClassName());
}
}
@Override
public void beforeAnalysis() {
analysisTime.start();
}
@Override
public void afterAnalysis() {
analysisTime.stop();
put(Headers.DataflowVisitedMethod, dataflowReachableMethods.size());
put(Headers.CryptoAnalysisTime_ms, analysisTime.elapsed(TimeUnit.MILLISECONDS));
put(Headers.SeedObjectCount, seeds);
Table<Class, CrySLRule, Integer> errorTable = HashBasedTable.create();
for(AbstractError err : errors){
Integer integer = errorTable.get(err.getClass(), err.getRule());
if(integer == null){
integer = 0;
}
integer++;
errorTable.put(err.getClass(), err.getRule(),integer);
}
for(Cell<Class, CrySLRule, Integer> c : errorTable.cellSet()){
put(c.getRowKey().getSimpleName() + "_" + c.getColumnKey().getClassName(), c.getValue());
}
Map<Class, Integer> errorsAccumulated = Maps.newHashMap();
for(Cell<Class, CrySLRule, Integer> c : errorTable.cellSet()){
Integer integer = errorsAccumulated.get(c.getRowKey());
if(integer == null){
integer = 0;
}
integer += c.getValue();
errorsAccumulated.put(c.getRowKey(),integer);
}
for(Entry<Class, Integer> c : errorsAccumulated.entrySet()){
put(c.getKey().getSimpleName() + "_sum", c.getValue());
}
writeToFile();
}
private void writeToFile() {
try {
FileWriter writer = new FileWriter(reportDir + File.separator+ REPORT_NAME);
writer.write(Joiner.on(CSV_SEPARATOR).join(headers) + "\n");
List<String> line = Lists.newArrayList();
for(String h : headers){
String string = headersToValues.get(h);
if(string == null){
string = "";
}
line.add(string);
}
writer.write(Joiner.on(CSV_SEPARATOR).join(line) + "\n");
writer.write("\n"+SARIFConfig.ANALYSISTOOL_NAME_VALUE+"\n");
String version = getClass().getPackage().getImplementationVersion();
if(version == null) {
version = "Version is not known";
}
writer.write(version);
writer.close();
LOGGER.info("CSV Report generated to file : "+ reportDir.getAbsolutePath() + File.separator+ REPORT_NAME);
} catch (IOException e) {
LOGGER.error("Could not write to " + reportDir.getAbsolutePath() + File.separator+ REPORT_NAME, e);
}
}
private void put(String key, Object val) {
if (!headers.contains(key)) {
LOGGER.error("Did not create a header to this value " + key);
} else {
if(val == null){
LOGGER.info(key+" is null");
}
else {
headersToValues.put(key, val.toString());
}
}
}
private void put(Headers key, Object val) {
put(key.toString(),val);
}
@Override
public void beforeConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void afterConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void beforePredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void afterPredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void seedStarted(IAnalysisSeed analysisSeedWithSpecification) {
// TODO Auto-generated method stub
}
@Override
public void boomerangQueryStarted(Query seed, BackwardQuery q) {
}
@Override
public void boomerangQueryFinished(Query seed, BackwardQuery q) {
}
@Override
public void reportError(AbstractError error) {
errors.add(error);
}
@Override
public void ensuredPredicates(Table<Statement, Val, Set<EnsuredCrySLPredicate>> existingPredicates,
Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> expectedPredicates,
Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> missingPredicates) {
}
@Override
public void checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification,
Collection<ISLConstraint> relConstraints) {
}
@Override
public void onSeedTimeout(Node<Statement, Val> seed) {
}
@Override
public void onSeedFinished(IAnalysisSeed seed, ForwardBoomerangResults<TransitionFunction> forwardResults) {
dataflowReachableMethods.addAll(forwardResults.getStats().getCallVisitedMethods());
}
@Override
public void collectedValues(AnalysisSeedWithSpecification seed,
Multimap<CallSiteWithParamIndex, ExtractedValue> collectedValues) {
}
@Override
public void discoveredSeed(IAnalysisSeed curr) {
seeds++;
}
@Override
public void onSecureObjectFound(IAnalysisSeed analysisObject) {
// TODO Auto-generated method stub
}
@Override
public void addProgress(int processedSeeds, int workListsize) {
// TODO Auto-generated method stub
}
}
| 9,687 | 31.07947 | 122 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/CollectErrorListener.java | package crypto.reporting;
import java.util.Collection;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.ForwardBoomerangResults;
import crypto.analysis.AnalysisSeedWithSpecification;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.ICrySLResultsListener;
import crypto.analysis.errors.AbstractError;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.extractparameter.ExtractedValue;
import crypto.interfaces.ISLConstraint;
import sync.pds.solver.nodes.Node;
import typestate.TransitionFunction;
public class CollectErrorListener implements ICrySLResultsListener {
private Collection<AbstractError> errors = Sets.newHashSet();
public void reportError(AbstractError error) {
errors.add(error);
}
public void checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification,
Collection<ISLConstraint> relConstraints) {
}
public void onSeedTimeout(Node<Statement, Val> seed) {
}
public void onSeedFinished(IAnalysisSeed seed, ForwardBoomerangResults<TransitionFunction> analysisResults) {
}
public void collectedValues(AnalysisSeedWithSpecification seed,
Multimap<CallSiteWithParamIndex, ExtractedValue> collectedValues) {
}
public void discoveredSeed(IAnalysisSeed curr) {
}
public void onSecureObjectFound(IAnalysisSeed analysisObject) {
}
public Collection<AbstractError> getErrors(){
return errors;
}
@Override
public void addProgress(int processedSeeds, int workListsize) {
// TODO Auto-generated method stub
}
}
| 1,636 | 24.578125 | 110 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/CommandLineReporter.java | package crypto.reporting;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import crypto.analysis.IAnalysisSeed;
import crypto.rules.CrySLRule;
public class CommandLineReporter extends ErrorMarkerListener {
private File outputFolder;
private List<CrySLRule> rules;
private Collection<IAnalysisSeed> objects = new HashSet<>();
/**
* The analysis report
*/
private String analysisReport;
/**
* Creates {@link CommandLineReporter} a constructor with reportDir and rules as parameter
*
* @param reportDir a {@link String} path giving the location of the report directory
* @param rules {@link CrySLRule} the rules with which the project is analyzed
*/
public CommandLineReporter(String reportDir, List<CrySLRule> rules) {
this.outputFolder = (reportDir != null ? new File(reportDir) : null);
this.rules = rules;
}
/**
* Creates {@link CommandLineReporter} a constructor with reportDir and rules as parameter
*
* @param rules {@link CrySLRule} the rules with which the project is analyzed
*/
public CommandLineReporter(List<CrySLRule> rules) {
this.rules = rules;
}
@Override
public void discoveredSeed(IAnalysisSeed object) {
this.objects.add(object);
}
@Override
public void afterAnalysis() {
this.analysisReport = ReporterHelper.generateReport(this.rules, this.objects, this.secureObjects, this.errorMarkers, this.errorMarkerCount);
System.out.println(analysisReport);
}
}
| 1,486 | 27.056604 | 142 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/ErrorMarkerListener.java | package crypto.reporting;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.base.CharMatcher;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import boomerang.BackwardQuery;
import boomerang.Query;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.ForwardBoomerangResults;
import crypto.analysis.AnalysisSeedWithSpecification;
import crypto.analysis.CrySLAnalysisListener;
import crypto.analysis.EnsuredCrySLPredicate;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.errors.AbstractError;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.ErrorVisitor;
import crypto.analysis.errors.ForbiddenMethodError;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.ImpreciseValueExtractionError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.NeverTypeOfError;
import crypto.analysis.errors.PredicateContradictionError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.extractparameter.ExtractedValue;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLPredicate;
import soot.SootClass;
import soot.SootMethod;
import sync.pds.solver.nodes.Node;
import typestate.TransitionFunction;
/**
* This listener is notified of any misuses the analysis finds.
*
* @author Stefan Krueger
* @author Johannes Spaeth
*
*/
public class ErrorMarkerListener extends CrySLAnalysisListener {
protected final Table<SootClass, SootMethod, Set<AbstractError>> errorMarkers = HashBasedTable.create();
protected final Map<Class, Integer> errorMarkerCount = new HashMap<Class, Integer>();
protected final List<IAnalysisSeed> secureObjects = new ArrayList<IAnalysisSeed>();
private void addMarker(AbstractError error) {
SootMethod method = error.getErrorLocation().getMethod();
SootClass sootClass = method.getDeclaringClass();
Set<AbstractError> set = errorMarkers.get(sootClass, method);
if(set == null){
set = Sets.newHashSet();
}
if(set.add(error)){
Integer integer = errorMarkerCount.get(error.getClass());
if(integer == null){
integer = 0;
}
integer++;
errorMarkerCount.put(error.getClass(), integer);
}
errorMarkers.put(sootClass, method, set);
}
@Override
public void reportError(AbstractError error) {
error.accept(new ErrorVisitor(){
@Override
public void visit(ConstraintError constraintError) {
addMarker(constraintError);
}
@Override
public void visit(ForbiddenMethodError forbiddenMethodError) {
addMarker(forbiddenMethodError);
}
@Override
public void visit(IncompleteOperationError incompleteOperationError) {
addMarker(incompleteOperationError);
}
@Override
public void visit(TypestateError typestateError) {
addMarker(typestateError);
}
@Override
public void visit(RequiredPredicateError predicateError) {
addMarker(predicateError);
}
@Override
public void visit(ImpreciseValueExtractionError extractionError) {
addMarker(extractionError);
}
@Override
public void visit(NeverTypeOfError neverTypeOfError) {
addMarker(neverTypeOfError);
}
@Override
public void visit(PredicateContradictionError predicateContradictionError) {
addMarker(predicateContradictionError);
}
@Override
public void visit(HardCodedError hardcodedError) {
addMarker(hardcodedError);
}});
}
@Override
public void afterAnalysis() {
// Nothing
}
@Override
public void afterConstraintCheck(final AnalysisSeedWithSpecification arg0) {
// nothing
}
@Override
public void afterPredicateCheck(final AnalysisSeedWithSpecification arg0) {
// Nothing
}
@Override
public void beforeAnalysis() {
// Nothing
}
@Override
public void beforeConstraintCheck(final AnalysisSeedWithSpecification arg0) {
// Nothing
}
@Override
public void beforePredicateCheck(final AnalysisSeedWithSpecification arg0) {
// Nothing
}
@Override
public void boomerangQueryFinished(final Query arg0, final BackwardQuery arg1) {
// Nothing
}
@Override
public void boomerangQueryStarted(final Query arg0, final BackwardQuery arg1) {
// Nothing
}
@Override
public void checkedConstraints(final AnalysisSeedWithSpecification arg0, final Collection<ISLConstraint> arg1) {
// Nothing
}
@Override
public void collectedValues(final AnalysisSeedWithSpecification arg0, final Multimap<CallSiteWithParamIndex, ExtractedValue> arg1) {
// Nothing
}
@Override
public void discoveredSeed(final IAnalysisSeed arg0) {
}
@Override
public void ensuredPredicates(final Table<Statement, Val, Set<EnsuredCrySLPredicate>> arg0, final Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> arg1, final Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> arg2) {
// Nothing
}
@Override
public void onSeedFinished(final IAnalysisSeed analysisObject, final ForwardBoomerangResults<TransitionFunction> arg1) {
}
@Override
public void onSecureObjectFound(final IAnalysisSeed analysisObject) {
secureObjects.add( analysisObject);
}
@Override
public void onSeedTimeout(final Node<Statement, Val> arg0) {
//Nothing
}
@Override
public void seedStarted(final IAnalysisSeed arg0) {
// Nothing
}
public static String filterQuotes(final String dirty) {
return CharMatcher.anyOf("\"").removeFrom(dirty);
}
@Override
public void addProgress(int processedSeeds, int workListsize) {
// TODO Auto-generated method stub
}
}
| 5,830 | 25.625571 | 224 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/ReporterHelper.java | package crypto.reporting;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.Table;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.errors.AbstractError;
import crypto.analysis.errors.ErrorWithObjectAllocation;
import crypto.rules.CrySLRule;
import soot.SootClass;
import soot.SootMethod;
public class ReporterHelper{
/** Generates analysis report content for {@link CommandLineReporter} CommandLineReporter and {@link TXTReporter} TXTReporter
* @param rules a {@link List} with {@link CrySLRule} rules
* @param objects a{@link Collection} with {@link IAnalysisSeed} objects
* @param secureObjects a {@link List} with {@link IAnalysisSeed} secureObjects
* @param errorMarkers a {@link Table} containing {@link SootClass},{@link SootMethod}
* and a {@link Set} of {@link AbstractError} of the errors found during analysis
* @param errorMarkerCount a {@link Map} containing {@link Class} class of error and
* {@link Integer} number of errors
* @return report {@link String} of the analysis
*/
public static String generateReport(List<CrySLRule> rules, Collection<IAnalysisSeed> objects,
List<IAnalysisSeed> secureObjects, Table<SootClass, SootMethod, Set<AbstractError>> errorMarkers,
Map<Class, Integer> errorMarkerCount){
String report = "";
report += "Ruleset: \n";
for (CrySLRule r : rules) {
report += String.format("\t%s\n", r.getClassName());
}
report += "\n";
report += "Analyzed Objects: \n";
for (IAnalysisSeed r : objects) {
report += String.format("\tObject:\n");
report += String.format("\t\tVariable: %s\n", r.var().value());
report += String.format("\t\tType: %s\n", r.getType());
report += String.format("\t\tStatement: %s\n", r.stmt().getUnit().get());
report += String.format("\t\tMethod: %s\n", r.getMethod());
report += String.format("\t\tSHA-256: %s\n", r.getObjectId());
report += String.format("\t\tSecure: %s\n", secureObjects.contains(r));
}
report += "\n";
for (SootClass c : errorMarkers.rowKeySet()) {
report += String.format("Findings in Java Class: %s\n", c.getName());
for (Entry<SootMethod, Set<AbstractError>> e : errorMarkers.row(c).entrySet()) {
report += String.format("\n\t in Method: %s\n", e.getKey().getSubSignature());
for (AbstractError marker : e.getValue()) {
report += String.format("\t\t%s violating CrySL rule for %s", marker.getClass().getSimpleName() ,marker.getRule().getClassName());
if(marker instanceof ErrorWithObjectAllocation) {
report += String.format(" (on Object #%s)\n", ((ErrorWithObjectAllocation) marker).getObjectLocation().getObjectId());
} else {
report += "\n";
}
report += String.format("\t\t\t%s\n", marker.toErrorMarkerString());
report += String.format("\t\t\tat statement: %s\n\n", marker.getErrorLocation().getUnit().get());
}
}
report += "\n";
}
report += "======================= CryptoAnalysis Summary ==========================\n";
report += String.format("\tNumber of CrySL rules: %s\n", rules.size());
report += String.format("\tNumber of Objects Analyzed: %s\n", objects.size());
if(errorMarkers.rowKeySet().isEmpty()){
report += "No violation of any of the rules found.\n";
} else{
report += "\n\tCryptoAnalysis found the following violations. For details see description above.\n";
for(Entry<Class, Integer> e : errorMarkerCount.entrySet()){
report += String.format("\t%s: %s\n", e.getKey().getSimpleName(),e.getValue());
}
}
report += "=====================================================================";
return report;
}
}
| 3,718 | 41.261364 | 135 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/SARIFConfig.java | package crypto.reporting;
public class SARIFConfig {
public static final String VERSION = "version";
public static final String SARIF_VERSION = "sarifVersion";
public static final String SARIF_VERSION_NUMBER = "2.0.0";
public static final String VERSION_NUMBER = "1.0.0";
public static final String RUNS_KEY = "runs";
public static final String TOOL_KEY = "tool";
public static final String TOOL_NAME_KEY = "name";
public static final String TOOL_NAME_VALUE = "CogniCrypt";
public static final String TOOL_FULL_NAME_KEY = "fullName";
public static final String TOOL_FULL_NAME_VALUE = "CogniCrypt (en-US)";
public static final String SEMANTIC_VERSION_KEY = "semanticVersion";
public static final String SEMANTIC_VERSION_VALUE = "1.0.0";
public static final String LANGUAGE_KEY = "language";
public static final String LANGUAGE_VALUE = "en-US";
public static final String ANALYSISTOOL_NAME_KEY = "name";
public static final String ANALYSISTOOL_NAME_VALUE = "CryptoAnalysis";
public static final String FILES_KEY = "files";
public static final String MIME_TYPE_KEY = "mimeType";
public static final String MIME_TYPE_VALUE = "text/java";
public static final String RESULTS_KEY = "results";
public static final String RULE_ID_KEY = "ruleId";
public static final String MESSAGE_KEY = "message";
public static final String TEXT_KEY = "text";
public static final String RICH_TEXT_KEY = "richText";
public static final String LOCATIONS_KEY = "locations";
public static final String PHYSICAL_LOCATION_KEY = "physicalLocation";
public static final String FILE_LOCATION_KEY = "fileLocation";
public static final String URI_KEY = "uri";
public static final String REGION_KEY = "region";
public static final String START_LINE_KEY = "startLine";
public static final String FULLY_QUALIFIED_LOGICAL_NAME_KEY = "fullyQualifiedLogicalName";
// public static final String
public static final String RESOURCES_KEY = "resources";
public static final String RULES_KEY = "rules";
public static final String RULES_ID_KEY = "id";
public static final String FULL_DESCRIPTION_KEY = "fullDescription";
//rules and their descriptions
public static final String CONSTRAINT_ERROR_KEY = "ConstraintError";
public static final String CONSTRAINT_ERROR_VALUE = "A constraint of a CrySL rule is violated, e.g., a key is generated with the wrong key size.";
public static final String NEVER_TYPE_OF_ERROR_KEY = "NeverTypeOfError";
public static final String NEVER_TYPE_OF_ERROR_VALUE = "Reported when a value was found to be of a certain reference type: For example, a character array containing a password should never be converted from a String";
public static final String HARDCODED_ERROR_KEY = "HardCodedError";
public static final String HARDCODED_ERROR_VALUE = "A hardcoded value was found. Load the value dynamically from a data storage.";
public static final String FORBIDDEN_METHOD_ERROR_KEY = "ForbiddenMethodError";
public static final String FORBIDDEN_METHOD_ERROR_VALUE = "A method that is forbidden (CrySL block FORBIDDEN) to be called under some circumstances was found.";
public static final String IMPRECISE_VALUE_EXTRACTION_ERROR_KEY = "ImpreciseValueExtractionError";
public static final String IMPRECISE_VALUE_EXTRACTION_ERROR_VALUE = "The static analysis was not able to extract all information required within the CrySL CONSTRAINT block. For example the key size could be supplied as a value listed in a configuration file. The static analysis does not model the file's content and may not constraint on the value.";
public static final String TYPE_STATE_ERROR_KEY = "TypestateError";
public static final String TYPE_STATE_ERROR_VALUE = "The ORDER block of CrySL is violated, i.e., the expected method sequence call to be made is incorrect. For example, a Signature object expects a call to initSign(key) prior to update(data).";
public static final String REQUIRED_PREDICATE_ERROR_KEY = "RequiredPredicateError";
public static final String REQUIRED_PREDICATE_ERROR_VALUE = "An object A expects an object B to have been used correctly (CrySL blocks REQUIRES and ENSURES). For example a Cipher object requires a SecretKey object to be correctly and securely generated.";
public static final String INCOMPLETE_OPERATION_ERROR_KEY = "IncompleteOperationError";
public static final String INCOMPLETE_OPERATION_ERROR_VALUE = "The usage of an object may be incomplete: For example a Cipherobject may be initialized but never used for en- or decryption, this may render the code dead. This error heavily depends on the computed call graph (CHA by default)";
public static final String INSTANCE_OF_ERROR_KEY = "InstanceOfError";
public static final String INSTANCE_OF_ERROR_VALUE = "Reported when a value was found to not be of a certain instance.";
}
| 4,798 | 70.626866 | 352 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/SARIFHelper.java | package crypto.reporting;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import soot.SootClass;
@SuppressWarnings("unchecked")
public class SARIFHelper {
private final Map<String, String> rulesMap = new HashMap<>();
private final SourceCodeLocater sourceLocater;
public SARIFHelper() {
initialize();
this.sourceLocater = null;
}
public SARIFHelper(SourceCodeLocater sourceLocater) {
this.sourceLocater = sourceLocater;
}
private void initialize() {
//SARIFConfig
this.rulesMap.put(SARIFConfig.CONSTRAINT_ERROR_KEY, SARIFConfig.CONSTRAINT_ERROR_VALUE);
this.rulesMap.put(SARIFConfig.FORBIDDEN_METHOD_ERROR_KEY, SARIFConfig.FORBIDDEN_METHOD_ERROR_VALUE);
this.rulesMap.put(SARIFConfig.IMPRECISE_VALUE_EXTRACTION_ERROR_KEY, SARIFConfig.IMPRECISE_VALUE_EXTRACTION_ERROR_VALUE);
this.rulesMap.put(SARIFConfig.INCOMPLETE_OPERATION_ERROR_KEY, SARIFConfig.INCOMPLETE_OPERATION_ERROR_VALUE);
this.rulesMap.put(SARIFConfig.NEVER_TYPE_OF_ERROR_KEY, SARIFConfig.NEVER_TYPE_OF_ERROR_VALUE);
this.rulesMap.put(SARIFConfig.REQUIRED_PREDICATE_ERROR_KEY, SARIFConfig.REQUIRED_PREDICATE_ERROR_VALUE);
this.rulesMap.put(SARIFConfig.TYPE_STATE_ERROR_KEY, SARIFConfig.TYPE_STATE_ERROR_VALUE);
}
public JSONObject initialJson() {
JSONObject json = new JSONObject();
json.put(SARIFConfig.VERSION, SARIFConfig.VERSION_NUMBER);
json.put(SARIFConfig.RUNS_KEY, new JSONArray().add(getRuns()));
return json;
}
private JSONObject getRuns() {
JSONObject jsonRuns = new JSONObject();
jsonRuns.put(SARIFConfig.TOOL_KEY, getToolInfo());
return jsonRuns;
}
public JSONObject getToolInfo() {
JSONObject tool = new JSONObject();
tool.put(SARIFConfig.ANALYSISTOOL_NAME_KEY, SARIFConfig.ANALYSISTOOL_NAME_VALUE);
tool.put(SARIFConfig.VERSION, getClass().getPackage().getImplementationVersion());
tool.put(SARIFConfig.SEMANTIC_VERSION_KEY,getClass().getPackage().getImplementationVersion());
tool.put(SARIFConfig.LANGUAGE_KEY, SARIFConfig.LANGUAGE_VALUE);
return tool;
}
public JSONObject getMessage(String text, String richText) {
JSONObject message = new JSONObject();
message.put(SARIFConfig.TEXT_KEY, text);
message.put(SARIFConfig.RICH_TEXT_KEY, richText);
return message;
}
public String getFileName(SootClass c) {
return sourceLocater == null ? c.getName().replace(".", "/") + ".java" : sourceLocater.getAbsolutePath(c);
}
public JSONArray getLocations(SootClass c, String methodName, int lineNumber) {
JSONArray locations = new JSONArray();
JSONObject location = new JSONObject();
JSONObject startLine = new JSONObject();
startLine.put(SARIFConfig.START_LINE_KEY, lineNumber);
JSONObject uri = new JSONObject();
uri.put(SARIFConfig.URI_KEY, getFileName(c));
JSONObject physicalLocation = new JSONObject();
physicalLocation.put(SARIFConfig.FILE_LOCATION_KEY, uri);
physicalLocation.put(SARIFConfig.REGION_KEY, startLine);
location.put(SARIFConfig.PHYSICAL_LOCATION_KEY, physicalLocation);
String fullyQualifiedLogicalName = c.getName().replace(".", "::") + "::" + methodName;
location.put(SARIFConfig.FULLY_QUALIFIED_LOGICAL_NAME_KEY, fullyQualifiedLogicalName);
locations.add(location);
return locations;
}
public String getRuleDescription(String ruleId) {
return this.rulesMap.get(ruleId);
}
}
| 3,378 | 34.946809 | 122 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/SARIFReporter.java | package crypto.reporting;
import java.io.File;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.errors.AbstractError;
import crypto.rules.CrySLRule;
import soot.SootClass;
import soot.SootMethod;
/**
* This class creates {@link SARIFReporter} a constructor with reportDir and rules as parameter
*
* @param reportDir a {@link String} path giving the location of the report directory
* @param rules {@link CrySLRule} the rules with which the project is analyzed
*/
@SuppressWarnings("unchecked")
public class SARIFReporter extends ErrorMarkerListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SARIFReporter.class);
private File outputFolder;
// private List<CrySLRule> rules;
private Collection<IAnalysisSeed> objects = new HashSet<>();
private JSONObject files = new JSONObject(), resources = new JSONObject(), rules = new JSONObject();
private JSONArray results = new JSONArray();
private SARIFHelper sarifHelper;
private Map<String, Integer> errorCountMap;
/**
* name of the analysis report
*/
private static final String REPORT_NAME = "CryptoAnalysis-Report.json";
public SARIFReporter(String reportDir, List<CrySLRule> rules) {
this.outputFolder = (reportDir != null ? new File(reportDir) : new File(System.getProperty("user.dir")));
this.sarifHelper = new SARIFHelper();
this.errorCountMap = new HashMap<String, Integer>();
initializeMap();
}
public SARIFReporter(String string, List<CrySLRule> rules, SourceCodeLocater sourceLocater) {
this(string, rules);
this.sarifHelper = new SARIFHelper(sourceLocater);
}
private void initializeMap() {
this.errorCountMap.put(SARIFConfig.CONSTRAINT_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.NEVER_TYPE_OF_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.HARDCODED_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.INSTANCE_OF_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.FORBIDDEN_METHOD_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.IMPRECISE_VALUE_EXTRACTION_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.TYPE_STATE_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.REQUIRED_PREDICATE_ERROR_KEY, 0);
this.errorCountMap.put(SARIFConfig.INCOMPLETE_OPERATION_ERROR_KEY, 0);
}
private void addFile(SootClass c) {
String filePath = this.sarifHelper.getFileName(c);
JSONObject mimeType = new JSONObject();
mimeType.put(SARIFConfig.MIME_TYPE_KEY, SARIFConfig.MIME_TYPE_VALUE);
this.files.put(filePath, mimeType);
}
private String addRules(String errorType) {
String finalErrorType = errorType;
if (this.rules.containsKey(errorType)) {
int count = this.errorCountMap.get(errorType);
count++;
finalErrorType = errorType.concat("-".concat(Integer.toString(count)));
this.errorCountMap.put(errorType, count);
}
JSONObject ruleInfo = new JSONObject();
JSONObject fullDescription = new JSONObject();
fullDescription.put(SARIFConfig.TEXT_KEY, this.sarifHelper.getRuleDescription(errorType));
ruleInfo.put(SARIFConfig.RULES_ID_KEY, errorType);
ruleInfo.put(SARIFConfig.FULL_DESCRIPTION_KEY, fullDescription);
this.rules.put(finalErrorType, ruleInfo);
return finalErrorType;
}
private void addResults(String errorType, SootClass c, String methodName, int lineNumber, String text,
String richText) {
JSONObject result = new JSONObject();
String finalErrorType = addRules(errorType);
result.put(SARIFConfig.RULE_ID_KEY, finalErrorType);
result.put(SARIFConfig.MESSAGE_KEY, this.sarifHelper.getMessage(text, richText));
result.put(SARIFConfig.LOCATIONS_KEY, this.sarifHelper.getLocations(c, methodName, lineNumber));
this.results.add(result);
}
private JSONObject makeSARIF() {
this.resources.put(SARIFConfig.RULES_KEY, this.rules);
JSONObject sarif = new JSONObject();
sarif.put(SARIFConfig.SARIF_VERSION, SARIFConfig.SARIF_VERSION_NUMBER);
JSONArray runs = new JSONArray();
JSONObject run = new JSONObject();
run.put(SARIFConfig.TOOL_KEY, this.sarifHelper.getToolInfo());
run.put(SARIFConfig.FILES_KEY, this.files);
run.put(SARIFConfig.RESULTS_KEY, this.results);
run.put(SARIFConfig.RESOURCES_KEY, this.resources);
runs.add(run);
sarif.put(SARIFConfig.RUNS_KEY, runs);
return sarif;
}
@Override
public void discoveredSeed(IAnalysisSeed object) {
this.objects.add(object);
}
@Override
public void afterAnalysis() {
for (SootClass c : this.errorMarkers.rowKeySet()) {
addFile(c);
for (Entry<SootMethod, Set<AbstractError>> e : this.errorMarkers.row(c).entrySet()) {
for (AbstractError marker : e.getValue()) {
String errorType = marker.getClass().getSimpleName();
String richText = String.format("%s violating CrySL rule for %s.",
marker.getClass().getSimpleName(), marker.getRule().getClassName());
String text = String.format("%s.", marker.toErrorMarkerString());
int lineNumber = marker.getErrorLocation().getUnit().get().getJavaSourceStartLineNumber();
this.addResults(errorType, c, e.getKey().getName(), lineNumber, text, richText);
}
}
}
JSONObject sarif = makeSARIF();
try {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
writer.writeValue(Paths.get(outputFolder + File.separator + REPORT_NAME).toFile(), sarif);
LOGGER.info("SARIF Report generated to file : "+ outputFolder + File.separator + REPORT_NAME);
} catch (IOException e) {
LOGGER.error("Could not write to file: "+outputFolder.getAbsolutePath() + File.separator+ REPORT_NAME, e);
}
}
}
| 6,067 | 37.163522 | 109 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/SourceCodeLocater.java | package crypto.reporting;
import java.io.File;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import soot.SootClass;
public class SourceCodeLocater {
private File baseDir;
public SourceCodeLocater(File baseDir) {
this.baseDir = baseDir;
}
public String getAbsolutePath(SootClass className) {
String shortName = className.getShortName();
Collection<File> files = FileUtils.listFiles(
baseDir,
new RegexFileFilter(shortName+".java"),
DirectoryFileFilter.DIRECTORY
);
for(File file : files) {
if(file.getAbsolutePath().contains(className.toString().replace(".", File.separator))) {
return file.getAbsolutePath();
}
}
return className +" (No source code found)";
}
}
| 865 | 23.742857 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/reporting/TXTReporter.java | package crypto.reporting;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import crypto.analysis.IAnalysisSeed;
import crypto.rules.CrySLRule;
import soot.Printer;
import soot.SootClass;
import soot.util.EscapedWriter;
public class TXTReporter extends ErrorMarkerListener{
private File outputFolder;
private List<CrySLRule> rules;
private Collection<IAnalysisSeed> objects = new HashSet<>();
private static final Logger LOG = LoggerFactory.getLogger(TXTReporter.class);
/**
* The report of the analysis
*/
private String analysisReport;
/**
* name of the analysis report
*/
private static final String REPORT_NAME = "CryptoAnalysis-Report.txt";
/**
* Creates {@link TXTReporter} a constructor with reportDir and rules as parameter
*
* @param reportDir a {@link String} path giving the location of the report directory
* @param rules {@link CrySLRule} the rules with which the project is analyzed
*/
public TXTReporter(String reportDir, List<CrySLRule> rules) {
this.outputFolder = (reportDir != null ? new File(reportDir) : new File(System.getProperty("user.dir")));
this.rules = rules;
}
@Override
public void discoveredSeed(IAnalysisSeed object) {
this.objects.add(object);
}
@Override
public void afterAnalysis() {
this.analysisReport = ReporterHelper.generateReport(rules, objects, this.secureObjects, this.errorMarkers, this.errorMarkerCount);
try {
FileWriter writer = new FileWriter(outputFolder + File.separator + REPORT_NAME);
writer.write(this.analysisReport);
writer.close();
for (SootClass c : this.errorMarkers.rowKeySet()) {
FileOutputStream streamOut = new FileOutputStream(new File(outputFolder + File.separator +c.toString()+".jimple"));
PrintWriter writerOut = new PrintWriter(new EscapedWriter(new OutputStreamWriter(streamOut)));
Printer.v().printTo(c, writerOut);
writerOut.flush();
streamOut.close();
writerOut.close();
}
LOG.info("Text Report generated to file : "+ outputFolder.getAbsolutePath() + File.separator + REPORT_NAME);
} catch (IOException e) {
LOG.error("Could not write to file " + outputFolder.getAbsolutePath() + File.separator+ REPORT_NAME, e);
}
}
}
| 2,453 | 32.616438 | 132 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLArithmeticConstraint.java | package crypto.rules;
import java.util.HashSet;
import java.util.Set;
import crypto.interfaces.ICrySLPredicateParameter;
public class CrySLArithmeticConstraint extends CrySLLiteral implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public enum ArithOp { p, n, m}
/* p = +
* n = -
* m = %
*/
private ArithOp operator;
private ICrySLPredicateParameter left;
private ICrySLPredicateParameter right;
public CrySLArithmeticConstraint(ICrySLPredicateParameter l, ICrySLPredicateParameter r, ArithOp op) {
left = l;
right = r;
operator = op;
}
/**
* @return the operator
*/
public ArithOp getOperator() {
return operator;
}
/**
* @return the left
*/
public ICrySLPredicateParameter getLeft() {
return left;
}
/**
* @return the right
*/
public ICrySLPredicateParameter getRight() {
return right;
}
public String toString() {
return left + " " + (operator.equals(ArithOp.p) ? "+" : (operator.equals(ArithOp.m) ? "%" : "-")) + " " + right;
}
@Override
public Set<String> getInvolvedVarNames() {
Set<String> varNames = new HashSet<String>();
String name = left.getName();
if(!isIntOrBoolean(name)) {
varNames.add(name);
}
name = right.getName();
if(!isIntOrBoolean(name)) {
varNames.add(name);
}
return varNames;
}
private boolean isIntOrBoolean(String name) {
try {
Integer.parseInt(name);
return true;
} catch(NumberFormatException ex) {
}
return name.equalsIgnoreCase("false") || name.equalsIgnoreCase("true");
}
@Override
public String getName() {
return toString();
}
}
| 1,622 | 18.321429 | 114 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLComparisonConstraint.java | package crypto.rules;
import java.util.Set;
public class CrySLComparisonConstraint extends CrySLLiteral implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public enum CompOp { l, g, le, ge, eq, neq}
private CompOp operator;
private CrySLArithmeticConstraint left;
private CrySLArithmeticConstraint right;
public CrySLComparisonConstraint(CrySLArithmeticConstraint l, CrySLArithmeticConstraint r, CompOp op) {
left = l;
right = r;
operator = op;
}
public String toString() {
return left + " " + getOperatorString() + " " + right;
}
/**
* @return
*/
private String getOperatorString() {
switch (operator) {
case l:
return "<";
case le:
return "<";
case g:
return ">";
case ge:
return ">=";
case neq:
return "!=";
default:
return "=";
}
}
/**
* @return the operator
*/
public CompOp getOperator() {
return operator;
}
/**
* @return the left
*/
public CrySLArithmeticConstraint getLeft() {
return left;
}
/**
* @return the right
*/
public CrySLArithmeticConstraint getRight() {
return right;
}
@Override
public Set<String> getInvolvedVarNames() {
Set<String> varNames = left.getInvolvedVarNames();
varNames.addAll(right.getInvolvedVarNames());
return varNames;
}
@Override
public String getName() {
return toString();
}
}
| 1,401 | 15.494118 | 104 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLCondPredicate.java | package crypto.rules;
import java.util.List;
import java.util.Set;
import crypto.interfaces.ICrySLPredicateParameter;
import crypto.interfaces.ISLConstraint;
public class CrySLCondPredicate extends CrySLPredicate {
/**
*
*/
private static final long serialVersionUID = 1L;
private final Set<StateNode> conditionalNodes;
public CrySLCondPredicate(ICrySLPredicateParameter baseObj, String name, List<ICrySLPredicateParameter> variables, Boolean not, Set<StateNode> label) {
this(baseObj, name, variables, not, label, null);
}
public CrySLCondPredicate(ICrySLPredicateParameter baseObj, String name, List<ICrySLPredicateParameter> variables, Boolean not, Set<StateNode> label, ISLConstraint cons) {
super(baseObj, name, variables, not, cons);
conditionalNodes = label;
}
/**
* @return the conditionalMethods
*/
public Set<StateNode> getConditionalMethods() {
return conditionalNodes;
}
public String toString() {
return "COND" + super.toString();
}
}
| 992 | 25.837838 | 172 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLConstraint.java | package crypto.rules;
import java.io.Serializable;
import java.util.Set;
import boomerang.jimple.Statement;
import crypto.interfaces.ISLConstraint;
public class CrySLConstraint implements ISLConstraint, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public enum LogOps { and , or , implies , eq}
private LogOps operator;
private ISLConstraint left;
private ISLConstraint right;
private Statement location;
public CrySLConstraint(ISLConstraint l, ISLConstraint r, LogOps op) {
left = l;
right = r;
operator = op;
}
/**
* @return the operator
return operator;
*/
public LogOps getOperator() {
return operator;
}
/**
* @return the left
*/
public ISLConstraint getLeft() {
return left;
}
/**
* @return the right
*/
public ISLConstraint getRight() {
return right;
}
public String toString() {
StringBuilder constraintSB = new StringBuilder();
constraintSB.append(left.toString());
constraintSB.append(operator);
constraintSB.append(right.toString());
return constraintSB.toString();
}
@Override
public Set<String> getInvolvedVarNames() {
Set<String> varNames = left.getInvolvedVarNames();
varNames.addAll(right.getInvolvedVarNames());
return varNames;
}
@Override
public String getName() {
return toString();
}
@Override
public void setLocation(Statement location) {
this.location = location;
}
@Override
public Statement getLocation() {
return location;
}
}
| 1,483 | 17.097561 | 70 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLForbiddenMethod.java | package crypto.rules;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class CrySLForbiddenMethod implements Serializable{
private static final long serialVersionUID = 1L;
private CrySLMethod meth;
private Boolean silent;// = false;
private List<CrySLMethod> alternate;
public CrySLForbiddenMethod(CrySLMethod method, Boolean silent) {
this(method, silent, new ArrayList<CrySLMethod>());
}
public CrySLForbiddenMethod(CrySLMethod method, Boolean silent, List<CrySLMethod> alternatives) {
this.meth = method;
this.silent = silent;
this.alternate = alternatives;
}
public CrySLMethod getMethod() {
return meth;
}
public Boolean getSilent() {
return silent;
}
public List<CrySLMethod> getAlternatives() {
return alternate;
}
public String toString() {
final StringBuilder forbMethod = new StringBuilder();
forbMethod.append(meth.toString());
forbMethod.append("( silent: " + silent + ")");
if (!alternate.isEmpty()) {
forbMethod.append(" Alternatives: ");
}
for (CrySLMethod meth : alternate) {
forbMethod.append(meth.toString());
}
return forbMethod.toString();
}
} | 1,175 | 22.058824 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLLiteral.java | package crypto.rules;
import java.io.Serializable;
import boomerang.jimple.Statement;
import crypto.interfaces.ISLConstraint;
public abstract class CrySLLiteral implements ISLConstraint, Serializable {
private static final long serialVersionUID = 1L;
private Statement location;
public void setLocation(Statement location) {
this.location = location;
}
public Statement getLocation() {
return location;
}
}
| 425 | 18.363636 | 75 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLMethod.java | package crypto.rules;
import java.io.Serializable;
import java.util.List;
import java.util.Map.Entry;
import crypto.interfaces.ICrySLPredicateParameter;
public class CrySLMethod implements Serializable, ICrySLPredicateParameter {
private static final long serialVersionUID = 1L;
private final String methodName;
private final Entry<String, String> retObject;
private final List<Entry<String, String>> parameters;
private final List<Boolean> backward;
public CrySLMethod(String methName, List<Entry<String, String>> pars, List<Boolean> backw, Entry<String, String> returnObject) {
methodName = methName;
parameters = pars;
backward = backw;
retObject = returnObject;
}
/**
* @return the FQ methodName
*/
public String getMethodName() {
return methodName;
}
/**
* @return the short methodName
*/
public String getShortMethodName() {
return methodName.substring(methodName.lastIndexOf(".") + 1);
}
/**
* @return the parameters
*/
public List<Entry<String, String>> getParameters() {
return parameters;
}
/**
* @return the backward
*/
public List<Boolean> getBackward() {
return backward;
}
public Entry<String, String> getRetObject() {
return retObject;
}
public String toString() {
return getName();
}
@Override
public String getName() {
StringBuilder stmntBuilder = new StringBuilder();
String returnValue = retObject.getKey();
if (!"_".equals(returnValue)) {
stmntBuilder.append(returnValue);
stmntBuilder.append(" = ");
}
stmntBuilder.append(this.methodName);
stmntBuilder.append("(");
for (Entry<String, String> par: parameters) {
stmntBuilder.append(" ");
stmntBuilder.append(par.getKey());
// if (backward != null && backward.size() == parameters.size()) {
// stmntBuilder.append(" (");
// stmntBuilder.append(backward.get(parameters.indexOf(par)));
// stmntBuilder.append("),");
// }
}
stmntBuilder.append(");");
return stmntBuilder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((backward == null) ? 0 : backward.hashCode());
result = prime * result + ((methodName == null) ? 0 : methodName.hashCode());
result = prime * result + ((parameters == null) ? 0 : parameters.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof CrySLMethod)) {
return false;
}
CrySLMethod other = (CrySLMethod) obj;
return this.getMethodName().equals(other.getMethodName()) && parameters.equals(other.parameters);
}
} | 2,666 | 22.394737 | 129 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLObject.java | package crypto.rules;
import java.io.Serializable;
import crypto.interfaces.ICrySLPredicateParameter;
public class CrySLObject implements Serializable, ICrySLPredicateParameter {
private static final long serialVersionUID = 1L;
private String varName;
private String javaType;
private CrySLSplitter splitter;
public CrySLObject(String name, String type) {
this(name, type, null);
}
public CrySLObject(String name, String type, CrySLSplitter part) {
varName = name;
javaType = type;
splitter = part;
}
/**
* @return the varName
*/
public String getVarName() {
return varName;
}
/**
* @return the splitter
*/
public CrySLSplitter getSplitter() {
return splitter;
}
public String toString() {
return varName + ((splitter != null) ? splitter.toString() : "");
}
@Override
public String getName() {
return varName;
}
public String getJavaType() {
return javaType;
}
}
| 928 | 16.528302 | 76 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLPredicate.java | package crypto.rules;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import crypto.interfaces.ICrySLPredicateParameter;
import crypto.interfaces.ISLConstraint;
public class CrySLPredicate extends CrySLLiteral implements java.io.Serializable {
private static final long serialVersionUID = 1L;
protected final ICrySLPredicateParameter baseObject;
protected final String predName;
protected final List<ICrySLPredicateParameter> parameters;
protected final boolean negated;
protected final ISLConstraint optConstraint;
public CrySLPredicate(ICrySLPredicateParameter baseObject, String name, List<ICrySLPredicateParameter> variables, Boolean not) {
this(baseObject, name, variables, not, null);
}
public CrySLPredicate(ICrySLPredicateParameter baseObject, String name, List<ICrySLPredicateParameter> variables, Boolean not, ISLConstraint constraint) {
this.baseObject = baseObject;
this.predName = name;
this.parameters = variables;
this.negated = not;
this.optConstraint = constraint;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((predName == null) ? 0 : predName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof CrySLPredicate)) {
return false;
}
CrySLPredicate other = (CrySLPredicate) obj;
if (predName == null) {
if (other.predName != null) {
return false;
}
} else if (!predName.equals(other.predName)) {
return false;
}
return true;
}
/**
* @return the baseObject
*/
public ICrySLPredicateParameter getBaseObject() {
return baseObject;
}
/**
* @return the predName
*/
public String getPredName() {
return predName;
}
/**
* @return the optConstraint
*/
public ISLConstraint getConstraint() {
return optConstraint;
}
/**
* @return the parameters
*/
public List<ICrySLPredicateParameter> getParameters() {
return parameters;
}
/**
* @return the negated
*/
public Boolean isNegated() {
return negated;
}
public String toString() {
StringBuilder predSB = new StringBuilder();
if (negated) {
predSB.append("!");
}
predSB.append(predName);
predSB.append("(");
for (ICrySLPredicateParameter parameter : parameters) {
predSB.append(parameter);
predSB.append(",");
}
predSB.reverse().deleteCharAt(0).reverse();
predSB.append(")");
return predSB.toString();
}
@Override
public Set<String> getInvolvedVarNames() {
Set<String> varNames = new HashSet<String>();
if (Arrays.asList(new String[] {"neverTypeOf", "instanceOf"}).contains(predName)) {
varNames.add(parameters.get(0).getName());
} else {
for (ICrySLPredicateParameter var : parameters) {
if (!("_".equals(var.getName()) || "this".equals(var.getName()) || var instanceof CrySLMethod)) {
varNames.add(var.getName());
}
}
}
if(getBaseObject() != null)
varNames.add(getBaseObject().getName());
return varNames;
}
public CrySLPredicate setNegated(boolean negated){
if (negated == this.negated) {
return this;
} else {
return new CrySLPredicate(baseObject, predName, parameters, negated);
}
}
@Override
public String getName() {
if (parameters.size() == 1) {
return parameters.get(0).getName();
} else {
return "";
}
}
}
| 3,436 | 21.913333 | 155 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLRule.java | package crypto.rules;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;
import com.google.common.collect.Sets;
import crypto.interfaces.ISLConstraint;
import soot.SootMethod;
public class CrySLRule implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String className;
private final List<Entry<String, String>> objects;
protected final List<CrySLForbiddenMethod> forbiddenMethods;
protected final StateMachineGraph usagePattern;
protected final List<ISLConstraint> constraints;
protected final List<CrySLPredicate> predicates;
public CrySLRule(String _className, List<Entry<String, String>> defObjects, List<CrySLForbiddenMethod> _forbiddenMethods, StateMachineGraph _usagePattern, List<ISLConstraint> _constraints, List<CrySLPredicate> _predicates) {
className = _className;
objects = defObjects;
forbiddenMethods = _forbiddenMethods;
usagePattern = _usagePattern;
constraints = _constraints;
predicates = _predicates;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof CrySLRule) {
return ((CrySLRule) obj).getClassName().equals(className);
}
return false;
}
public boolean isLeafRule() {
for (ISLConstraint con : constraints) {
if (con instanceof CrySLPredicate) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
return 31 * className.hashCode();
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
/**
* @return the objects
*/
public List<Entry<String, String>> getObjects() {
return objects;
}
/**
* @return the forbiddenMethods
*/
public List<CrySLForbiddenMethod> getForbiddenMethods() {
return forbiddenMethods;
}
/**
* @return the usagePattern
*/
public StateMachineGraph getUsagePattern() {
return usagePattern;
}
/**
* @return the constraints
*/
public List<ISLConstraint> getConstraints() {
return constraints;
}
/**
* @return the predicates
*/
public List<CrySLPredicate> getPredicates() {
return predicates;
}
/**
* @return the constraints
*/
public List<CrySLPredicate> getRequiredPredicates() {
List<CrySLPredicate> requires = new LinkedList<CrySLPredicate>();
for (ISLConstraint con : constraints) {
if (con instanceof CrySLPredicate) {
requires.add((CrySLPredicate) con);
}
}
return requires;
}
public String toString() {
StringBuilder outputSB = new StringBuilder();
outputSB.append(this.className);
outputSB.append("\nforbiddenMethods:");
for (CrySLForbiddenMethod forbMethSig : this.forbiddenMethods) {
outputSB.append(forbMethSig);
outputSB.append(",");
}
outputSB.append("\nUsage Pattern:");
outputSB.append(this.usagePattern);
outputSB.append("\nConstraints:");
for (ISLConstraint constraint : this.constraints) {
outputSB.append(constraint);
outputSB.append(",");
}
if (this.predicates != null) {
outputSB.append("\nPredicates:");
for (CrySLPredicate predicate : this.predicates) {
outputSB.append(predicate);
outputSB.append(",");
}
}
return outputSB.toString();
}
public static Collection<String> toSubSignatures(Collection<SootMethod> methods) {
Set<String> subSignatures = Sets.newHashSet();
for(SootMethod m : methods){
subSignatures.add(m.getName());
}
return subSignatures;
}
}
| 3,490 | 20.417178 | 225 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLRuleReader.java | package crypto.rules;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import crypto.cryslhandler.CrySLModelReader;
import crypto.exceptions.CryptoAnalysisException;
public class CrySLRuleReader {
private static CrySLModelReader csmr;
private static CrySLModelReader getReader(){
if (csmr == null)
{
try {
csmr = new CrySLModelReader();
}
catch (MalformedURLException e){
e.printStackTrace();
}
}
return csmr;
}
/**
* Returns a {@link CrySLRule} read from a single CrySL file.
*
* @param file the CrySL file
* @return the {@link CrySLRule} object
* @throws CryptoAnalysisException Throws when a file could not get processed to a {@link CrySLRule}
*/
public static CrySLRule readFromSourceFile(File file) throws CryptoAnalysisException {
return getReader().readRule(file);
}
/**
* Returns a {@link List} of {@link CrySLRule} objects read from a directory
*
* @param directory the {@link File} with the directory where the rules are located
* @return the {@link List} with {@link CrySLRule} objects. If no rules are found it returns an empty list.
* @throws CryptoAnalysisException Throws when a file could not get processed to a {@link CrySLRule}
*/
public static List<CrySLRule> readFromDirectory(File directory) throws CryptoAnalysisException {
return readFromDirectory(directory, false);
}
/**
* Returns a {@link List} of {@link CrySLRule} objects read from a directory.
* In the case the directory contains further sub directories, they can also searched
* if the recursive argument is <code>true</code>.
*
* @param directory the {@link File} with the directory where the rules are located
* @param recursive <code>true</code> the subfolders will be searched too
* @return the {@link List} with {@link CrySLRule} objects. If no rules are found it returns an empty list.
* @throws CryptoAnalysisException Throws when a file could not get processed to a {@link CrySLRule}
*/
public static List<CrySLRule> readFromDirectory(File directory, boolean recursive) throws CryptoAnalysisException {
Map<String, CrySLRule> ruleMap = new HashMap<String, CrySLRule>();
if (!directory.exists() || !directory.isDirectory())
throw new CryptoAnalysisException("The specified path is not a directory " + directory.getAbsolutePath());
List<File> cryptSLFiles = new ArrayList<>();
findCryptSLFiles(directory, recursive, cryptSLFiles);
CrySLModelReader reader = getReader();
for (File file : cryptSLFiles) {
CrySLRule rule = reader.readRule(file);
if(rule != null) {
if(!ruleMap.containsKey(rule.getClassName())) {
ruleMap.put(rule.getClassName(), rule);
}
}
}
return new ArrayList<>(ruleMap.values());
}
/**
* Returns a {@link List} of {@link CrySLRule} objects read from a Zip {@link File}.
* @param file Zip that contains the CrySL files
* @return the {@link List} with {@link CrySLRule} objects. If no rules are found it returns an empty list.
* @throws CryptoAnalysisException
*/
public static List<CrySLRule> readFromZipFile(File file) throws CryptoAnalysisException {
if (!file.exists() || !file.isFile() || !file.getName().endsWith(".zip"))
throw new CryptoAnalysisException("The specified path is not a ZIP file " + file.getAbsolutePath());
Map<String, CrySLRule> ruleMap = new HashMap<String, CrySLRule>();
try {
ZipFile zip = new ZipFile(file);
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory()) {
CrySLRule rule = getCrySLRuleFromZipEntry(entry, zip, file);
if(rule != null) {
if(!ruleMap.containsKey(rule.getClassName())) {
ruleMap.put(rule.getClassName(), rule);
}
}
}
}
}
catch (IOException e) {
throw new CryptoAnalysisException(e.getMessage());
}
return new ArrayList<>(ruleMap.values());
}
private static void findCryptSLFiles(File directory, boolean recursive, Collection<File> resultCollection) {
for (File file: directory.listFiles())
{
if (file.isFile() && file.getName().endsWith(CrySLModelReader.cryslFileEnding))
resultCollection.add(file);
if (recursive && file.isDirectory())
findCryptSLFiles(file, recursive, resultCollection);
}
}
private static CrySLRule getCrySLRuleFromZipEntry(ZipEntry entry, ZipFile zip, File zipFile) throws CryptoAnalysisException
{
if (entry.isDirectory() || !entry.getName().endsWith(CrySLModelReader.cryslFileEnding))
throw new CryptoAnalysisException("ZIP entry is a directory or not a CrySL file");
CrySLRule rule = null;
try {
String name = createUniqueZipEntryName(zipFile, entry);
rule = getReader().readRule(zip.getInputStream(entry), name);
}
catch (IllegalArgumentException | IOException | NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return rule;
}
// For zip file entries there is no real URI. Using the raw absolute path of the zip file will cause a exception
// when trying to resolve/create the resource in the CrySLModelReader:readRule() methods.
// Solution: Create a custom URI with the following scheme:
// uri := [HexHashedAbsoluteZipFilePath][SystemFileSeparator][ZipEntryName]
// This scheme has the properties that it still is unique system-wide,
// The hash will be the same for the same file, so you could know if two rules come from the same ruleset file
// and you still can get the information of the zipped file.
private static String createUniqueZipEntryName(File zipFile, ZipEntry zipEntry) throws NoSuchAlgorithmException, CryptoAnalysisException {
if (!zipFile.exists() || !zipFile.isFile() || zipEntry == null)
throw new CryptoAnalysisException("The specified path is not a ZIP file " + zipFile.getAbsolutePath());
StringBuilder sb = new StringBuilder();
String partFileName;
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(zipFile.getAbsolutePath().getBytes());
partFileName = bytesToHex(messageDigest.digest());
sb.append(partFileName);
sb.append(File.separator);
sb.append(zipEntry.getName());
return sb.toString();
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes)
sb.append(String.format("%02x", b));
return sb.toString();
}
}
| 6,695 | 35 | 139 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLSplitter.java | package crypto.rules;
import java.io.Serializable;
public class CrySLSplitter implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int index = 0;
private String split = "";
public CrySLSplitter(int ind, String spl) {
this.index = ind;
this.split = spl;
}
public int getIndex() {
return index;
}
public String getSplitter() {
return split;
}
public String toString() {
return "( Split with " + split + " at index " + index + ")";
}
}
| 512 | 15.03125 | 62 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/CrySLValueConstraint.java | package crypto.rules;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CrySLValueConstraint extends CrySLLiteral implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
CrySLObject var;
List<String> valueRange;
public CrySLValueConstraint(CrySLObject name, String value) {
var = name;
valueRange = new ArrayList<String>();
valueRange.add(value);
}
public CrySLValueConstraint(CrySLObject name, List<String> values) {
var = name;
valueRange = values;
}
/**
* @return the varName
*/
public String getVarName() {
return var.getVarName();
}
/**
* @return the varName
*/
public CrySLObject getVar() {
return var;
}
/**
* @return the valueRange
*/
public List<String> getValueRange() {
return valueRange;
}
public String toString() {
StringBuilder vCSB = new StringBuilder();
vCSB.append("VC:");
vCSB.append(var);
vCSB.append(" - ");
for (String value : valueRange) {
vCSB.append(value);
vCSB.append(",");
}
return vCSB.toString();
}
@Override
public Set<String> getInvolvedVarNames() {
Set<String> varNames = new HashSet<String>();
varNames.add(var.getVarName());
return varNames;
}
@Override
public String getName() {
return toString();
}
}
| 1,344 | 16.933333 | 88 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/ParEqualsPredicate.java | package crypto.rules;
import java.util.ArrayList;
import java.util.List;
import crypto.interfaces.ICrySLPredicateParameter;
import crypto.interfaces.ISLConstraint;
public class ParEqualsPredicate extends CrySLPredicate {
public ParEqualsPredicate(ICrySLPredicateParameter baseObject, String name, List<ICrySLPredicateParameter> variables, Boolean not) {
this(baseObject, name, variables, not, null);
}
public ParEqualsPredicate(ICrySLPredicateParameter baseObject, String name, List<ICrySLPredicateParameter> variables, Boolean not, ISLConstraint constraint) {
super(baseObject, name, variables, not, constraint);
}
public CrySLPredicate tobasicPredicate() {
return new CrySLPredicate(baseObject, predName, parameters, negated, optConstraint);
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
CrySLPredicate other = (CrySLPredicate) obj;
List<ICrySLPredicateParameter> otherParams = new ArrayList<>(other.getParameters());
if (otherParams.size() == parameters.size()) {
otherParams.removeAll(parameters);
return otherParams.isEmpty();
}
return false;
}
}
| 1,147 | 27.7 | 159 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/StateMachineGraph.java | package crypto.rules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import crypto.interfaces.FiniteStateMachine;
public final class StateMachineGraph implements FiniteStateMachine<StateNode>, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private final Set<StateNode> nodes;
private final List<TransitionEdge> edges;
private int nodeNameCounter = 0;
public StateMachineGraph() {
nodes = new HashSet<StateNode>();
edges = new ArrayList<TransitionEdge>();
}
public StateNode createNewNode() {
StateNode node = new StateNode(String.valueOf(this.nodeNameCounter++), false, false);
this.nodes.add(node);
return node;
}
public boolean createNewEdge(List<CrySLMethod> methods, StateNode left, StateNode right) {
return this.addEdge(new TransitionEdge(methods, left, right));
}
private Boolean addEdge(TransitionEdge edge) {
final StateNode right = edge.getRight();
final StateNode left = edge.getLeft();
if (!(nodes.parallelStream().anyMatch(e -> e.equals(left)) || nodes.parallelStream().anyMatch(e -> e.equals(right)))) {
return false;
}
if (edges.contains(edge)) {
return false;
}
edges.add(edge);
return true;
}
public void wrapUpCreation() {
getAcceptingStates().parallelStream().forEach(e -> {
e.setHopsToAccepting(0);
updateHops(e);
});
}
public Set<TransitionEdge> getAllOutgoingEdges(StateNode node){
return edges.parallelStream().filter(edge -> edge.from().equals(node)).collect(Collectors.toSet());
}
public void addAllOutgoingEdgesFromOneNodeToOtherNodes(StateNode node, Collection<StateNode> otherNodes) {
List<TransitionEdge> edgesFromNode = edges.parallelStream().filter(e -> node.equals(e.from())).collect(Collectors.toList());
otherNodes.forEach(otherNode -> edgesFromNode.forEach(edge -> this.createNewEdge(edge.getLabel(), otherNode, edge.getLeft())));
}
public StateNode aggregateNodesToOneNode(Set<StateNode> endNodes, StateNode newNode) {
this.aggregateNodestoOtherNodes(endNodes, Lists.newArrayList(newNode));
return newNode;
}
public Collection<StateNode> aggregateNodestoOtherNodes(Collection<StateNode> nodesToAggr, Collection<StateNode> startNodes){
List<TransitionEdge> edgesToAnyAggrNode = edges.parallelStream().filter(e -> nodesToAggr.contains(e.to())).collect(Collectors.toList());
// Add new edges to newNode instead of Aggr Node
startNodes.forEach(node -> edgesToAnyAggrNode.forEach(edgeToAggrNode -> this.createNewEdge(edgeToAggrNode.getLabel(), edgeToAggrNode.getLeft(), node)));
nodesToAggr.removeAll(startNodes);
removeNodesWithAllEdges(nodesToAggr);
return startNodes;
}
private void removeNodesWithAllEdges(Collection<StateNode> nodesToRemove) {
nodesToRemove.forEach(node -> removeNodeWithAllEdges(node));
}
private void removeNodeWithAllEdges(StateNode node) {
removeAllEdgesHavingNode(node);
nodes.remove(node);
}
private void removeAllEdgesHavingNode(StateNode node) {
List<TransitionEdge> filteredEdges = edges.parallelStream().filter(e -> node.equals(e.to()) || node.equals(e.from())).collect(Collectors.toList());
edges.removeAll(filteredEdges);
}
private void updateHops(StateNode node) {
int newPath = node.getHopsToAccepting() + 1;
getAllTransitions().parallelStream().forEach(e -> {
StateNode theNewRight = e.getLeft();
if (e.getRight().equals(node) && theNewRight.getHopsToAccepting() > newPath) {
theNewRight.setHopsToAccepting(newPath);
updateHops(theNewRight);
}
});
}
public Boolean addNode(StateNode node) {
return nodes.parallelStream().anyMatch(n -> n.getName().equals(node.getName())) ? false : nodes.add(node);
}
public String toString() {
StringBuilder graphSB = new StringBuilder();
for (StateNode node : nodes) {
graphSB.append(node.toString());
graphSB.append(System.lineSeparator());
}
for (TransitionEdge te : edges) {
graphSB.append(te.toString());
graphSB.append(System.lineSeparator());
}
return graphSB.toString();
}
public Set<StateNode> getNodes() {
return nodes;
}
public List<TransitionEdge> getEdges() {
return edges;
}
public TransitionEdge getInitialTransition() {
return edges.get(0);
}
public Collection<StateNode> getAcceptingStates() {
return nodes.parallelStream().filter(node -> node.getAccepting()).collect(Collectors.toList());
}
public Collection<TransitionEdge> getAllTransitions() {
return getEdges();
}
}
| 4,602 | 30.527397 | 154 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/StateMachineGraphReader.java | package crypto.rules;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class StateMachineGraphReader {
public static StateMachineGraph readFromFile(File file) {
StateMachineGraph smg = null;
try {
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
smg = (StateMachineGraph) in.readObject();
System.err.println(smg);
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return smg;
}
}
| 602 | 22.192308 | 58 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/StateNode.java | package crypto.rules;
public class StateNode implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String name;
private Boolean init = false;
private Boolean accepting = false;
private int hopsToAccepting = Integer.MAX_VALUE;
public StateNode(String _name) {
name = _name;
}
public StateNode(String _name, Boolean _init) {
this(_name);
init = _init;
}
public StateNode(String _name, Boolean _init, Boolean _accepting) {
this(_name, _init);
accepting = _accepting;
}
public String getName() {
return name;
}
public Boolean getInit() {
return init;
}
public Boolean getAccepting() {
return accepting;
}
public void setAccepting(Boolean _accepting) {
accepting = _accepting;
}
public String toString() {
StringBuilder nodeSB = new StringBuilder();
nodeSB.append("Name: ");
nodeSB.append(name);
nodeSB.append(" (");
if (!accepting) {
nodeSB.append(hopsToAccepting + "hops to ");
}
nodeSB.append("accepting)");
return nodeSB.toString();
}
public boolean isErrorState() {
return !accepting;
}
public boolean isInitialState() {
return init;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accepting == null) ? 0 : accepting.hashCode());
result = prime * result + ((init == null) ? 0 : init.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateNode other = (StateNode) obj;
if (accepting == null) {
if (other.accepting != null)
return false;
} else if (!accepting.equals(other.accepting))
return false;
if (init == null) {
if (other.init != null)
return false;
} else if (!init.equals(other.init))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public void setHopsToAccepting(int hops) {
hopsToAccepting = hops;
}
public int getHopsToAccepting() {
return hopsToAccepting;
}
}
| 2,250 | 19.098214 | 77 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/rules/TransitionEdge.java | package crypto.rules;
import java.util.List;
import crypto.interfaces.Transition;
public class TransitionEdge implements Transition<StateNode>, java.io.Serializable {
private static final long serialVersionUID = 1L;
private StateNode left = null;
private StateNode right = null;
private List<CrySLMethod> methods = null;
public TransitionEdge(List<CrySLMethod> _methods, StateNode _left, StateNode _right) {
left = _left;
right = _right;
methods = _methods;
}
public StateNode getLeft() {
return left;
}
public StateNode getRight() {
return right;
}
public List<CrySLMethod> getLabel() {
return methods;
}
public String toString() {
StringBuilder edgeSB = new StringBuilder();
edgeSB.append("Left: ");
edgeSB.append(this.left.getName());
edgeSB.append(" ====");
edgeSB.append(methods);
edgeSB.append("====> Right:");
edgeSB.append(this.right.getName());
return edgeSB.toString();
}
public StateNode from() {
return left;
}
public StateNode to() {
return right;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((methods == null) ? 0 : methods.hashCode());
result = prime * result + ((left == null) ? 0 : left.hashCode());
result = prime * result + ((right == null) ? 0 : right.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TransitionEdge other = (TransitionEdge) obj;
if (methods == null) {
if (other.methods != null)
return false;
} else if (!methods.equals(other.methods))
return false;
if (left == null) {
if (other.left != null)
return false;
} else if (!left.equals(other.left))
return false;
if (right == null) {
if (other.right != null)
return false;
} else if (!right.equals(other.right))
return false;
return true;
}
}
| 1,961 | 21.295455 | 87 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/CrySLMethodToSootMethod.java | package crypto.typestate;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import crypto.rules.CrySLMethod;
import heros.utilities.DefaultValueMap;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
public class CrySLMethodToSootMethod {
private static final Logger LOGGER = LoggerFactory.getLogger(CrySLMethodToSootMethod.class);
private static CrySLMethodToSootMethod instance;
private DefaultValueMap<CrySLMethod, Collection<SootMethod>> descriptorToSootMethod = new DefaultValueMap<CrySLMethod, Collection<SootMethod>>() {
@Override
protected Collection<SootMethod> createItem(CrySLMethod key) {
Collection<SootMethod> res = Sets.newHashSet();
try{
res = _convert(key);
} catch(Exception e){
LOGGER.error("Failed to convert method " + key);
}
for (SootMethod m : res) {
sootMethodToDescriptor.put(m, key);
}
return res;
}
};
private Multimap<SootMethod, CrySLMethod> sootMethodToDescriptor = HashMultimap.create();
public Collection<CrySLMethod> convert(SootMethod m) {
return sootMethodToDescriptor.get(m);
}
public Collection<SootMethod> convert(CrySLMethod label) {
return descriptorToSootMethod.getOrCreate(label);
}
private Collection<SootMethod> _convert(CrySLMethod label) {
Set<SootMethod> res = Sets.newHashSet();
String methodName = label.getMethodName();
String declaringClass = getDeclaringClass(methodName);
// Scene.v().forceResolve(declaringClass, SootClass.BODIES);
if (!Scene.v().containsClass(declaringClass)){
return res;
}
SootClass sootClass = Scene.v().getSootClass(declaringClass);
List<SootClass> classes = Lists.newArrayList(sootClass);
String methodNameWithoutDeclaringClass = getMethodNameWithoutDeclaringClass(methodName);
if (methodNameWithoutDeclaringClass.equals(sootClass.getShortName())) {
//Constructors are only searched from within the actual class itself
methodNameWithoutDeclaringClass = "<init>";
} else {
//For all other EVENTS, any call of the hierarchy matches.
classes.addAll(getFullHierarchyOf(sootClass));
}
int noOfParams = label.getParameters().size();
for(SootClass c : classes) {
for (SootMethod m : c.getMethods()) {
if (m.getName().equals(methodNameWithoutDeclaringClass) && m.getParameterCount() == noOfParams) {
if (parametersMatch(label.getParameters(), m.getParameterTypes())){
res.add(m);
}
}
}
}
if(res.isEmpty()){
LOGGER.warn("Couldn't find any method for CrySLMethod: " + label);
}
return res;
}
private Collection<? extends SootClass> getFullHierarchyOf(SootClass sootClass) {
LinkedList<SootClass> worklist = Lists.newLinkedList();
Set<SootClass> visited = Sets.newHashSet();
worklist.add(sootClass);
visited.add(sootClass);
while (!worklist.isEmpty()) {
SootClass first = worklist.pop();
Set<SootClass> hierarchy = Sets.newHashSet();
hierarchy.addAll(first.getInterfaces());
if (first.isInterface()) {
hierarchy.addAll(Scene.v().getActiveHierarchy().getSuperinterfacesOf(first));
} else {
hierarchy.addAll(Scene.v().getActiveHierarchy().getSuperclassesOf(first));
}
for (SootClass h : hierarchy) {
if (visited.add(h)) {
worklist.add(h);
}
}
}
return visited;
}
private boolean parametersMatch(List<Entry<String, String>> parameters, List<Type> parameterTypes) {
int i = 0;
for (Type t : parameterTypes) {
if (parameters.get(i).getValue().equals("AnyType"))
continue;
if (!t.toString().equals(parameters.get(i).getValue())) {
return false;
}
i++;
}
return true;
}
private String getMethodNameWithoutDeclaringClass(String desc) {
return desc.substring(desc.lastIndexOf(".") + 1);
}
public Collection<SootMethod> convert(List<CrySLMethod> list) {
Set<SootMethod> res = Sets.newHashSet();
for (CrySLMethod l : list)
res.addAll(convert(l));
return res;
}
private String getDeclaringClass(String label) {
try {
if (Scene.v().containsClass(label))
return label;
} catch (RuntimeException e) {
}
return label.substring(0, label.lastIndexOf("."));
}
public static CrySLMethodToSootMethod v() {
if (instance == null)
instance = new CrySLMethodToSootMethod();
return instance;
}
public static void reset() {
instance = null;
}
}
| 4,804 | 29.801282 | 147 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/ErrorStateNode.java | package crypto.typestate;
import typestate.finiteautomata.State;
public class ErrorStateNode implements State {
public ErrorStateNode() {
}
@Override
public boolean isErrorState() {
return true;
}
@Override
public boolean isInitialState() {
return false;
}
@Override
public boolean isAccepting() {
return false;
}
@Override
public String toString() {
return "ERR";
}
@Override
public int hashCode() {
return this.getClass().hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof ErrorStateNode;
}
}
| 569 | 13.25 | 46 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/ExtendedIDEALAnaylsis.java | package crypto.typestate;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Maps;
import boomerang.BoomerangOptions;
import boomerang.ForwardQuery;
import boomerang.Query;
import boomerang.WeightedForwardQuery;
import boomerang.callgraph.ObservableICFG;
import boomerang.debugger.Debugger;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.ForwardBoomerangResults;
import crypto.analysis.CrySLResultsReporter;
import crypto.analysis.IAnalysisSeed;
import crypto.boomerang.CogniCryptBoomerangOptions;
import ideal.IDEALAnalysis;
import ideal.IDEALAnalysisDefinition;
import ideal.IDEALSeedSolver;
import ideal.IDEALSeedTimeout;
import soot.MethodOrMethodContext;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.util.queue.QueueReader;
import sync.pds.solver.WeightFunctions;
import typestate.TransitionFunction;
public abstract class ExtendedIDEALAnaylsis {
private FiniteStateMachineToTypestateChangeFunction changeFunction;
private final IDEALAnalysis<TransitionFunction> analysis;
private ForwardBoomerangResults<TransitionFunction> results;
private HashSet seeds;
public ExtendedIDEALAnaylsis(){
analysis = new IDEALAnalysis<TransitionFunction>(new IDEALAnalysisDefinition<TransitionFunction>() {
@Override
public Collection<WeightedForwardQuery<TransitionFunction>> generate(SootMethod method, Unit stmt) {
return getOrCreateTypestateChangeFunction().generateSeed(method, stmt);
}
@Override
public WeightFunctions<Statement, Val, Statement, TransitionFunction> weightFunctions() {
return getOrCreateTypestateChangeFunction();
}
@Override
public ObservableICFG<Unit, SootMethod> icfg() {
return ExtendedIDEALAnaylsis.this.icfg();
}
@Override
public boolean enableStrongUpdates() {
return true;
}
@Override
public Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver) {
return ExtendedIDEALAnaylsis.this.debugger(solver);
}
@Override
public BoomerangOptions boomerangOptions() {
return new CogniCryptBoomerangOptions();
}
});
}
private FiniteStateMachineToTypestateChangeFunction getOrCreateTypestateChangeFunction() {
if (this.changeFunction == null)
this.changeFunction = new FiniteStateMachineToTypestateChangeFunction(getStateMachine());
return this.changeFunction;
}
public abstract SootBasedStateMachineGraph getStateMachine();
public void run(ForwardQuery query) {
CrySLResultsReporter reports = analysisListener();
try {
results = analysis.run(query);
} catch (IDEALSeedTimeout e){
if (reports != null && query instanceof IAnalysisSeed) {
reports.onSeedTimeout(((IAnalysisSeed)query).asNode());
}
}
}
protected abstract ObservableICFG<Unit, SootMethod> icfg();
protected abstract Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver);
public void log(String string) {
// System.out.println(string);
}
public abstract CrySLResultsReporter analysisListener();
public Collection<WeightedForwardQuery<TransitionFunction>> computeSeeds(SootMethod method) {
Collection<WeightedForwardQuery<TransitionFunction>> seeds = new HashSet<>();
if (!method.hasActiveBody())
return seeds;
for (Unit u : method.getActiveBody().getUnits()) {
seeds.addAll( getOrCreateTypestateChangeFunction().generateSeed(method, u));
}
return seeds;
}
/**
* Only use this method for testing
* @return
*/
public Map<WeightedForwardQuery<TransitionFunction>, ForwardBoomerangResults<TransitionFunction>> run() {
Set<WeightedForwardQuery<TransitionFunction>> seeds = new HashSet<>();
ReachableMethods rm = Scene.v().getReachableMethods();
QueueReader<MethodOrMethodContext> listener = rm.listener();
while (listener.hasNext()) {
MethodOrMethodContext next = listener.next();
seeds.addAll(computeSeeds(next.method()));
}
Map<WeightedForwardQuery<TransitionFunction>, ForwardBoomerangResults<TransitionFunction>> seedToSolver = Maps.newHashMap();
for (Query s : seeds) {
if(s instanceof WeightedForwardQuery){
WeightedForwardQuery<TransitionFunction> seed = (WeightedForwardQuery<TransitionFunction>) s;
run((WeightedForwardQuery<TransitionFunction>)seed);
if(getResults() != null){
seedToSolver.put(seed, getResults());
}
}
}
return seedToSolver;
}
public ForwardBoomerangResults<TransitionFunction> getResults() {
return results;
}
} | 4,661 | 31.375 | 126 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/FiniteStateMachineToTypestateChangeFunction.java | package crypto.typestate;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import boomerang.WeightedForwardQuery;
import boomerang.jimple.AllocVal;
import boomerang.jimple.Statement;
import soot.RefType;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
import typestate.TransitionFunction;
import typestate.finiteautomata.MatcherTransition;
import typestate.finiteautomata.State;
import typestate.finiteautomata.TypeStateMachineWeightFunctions;
public class FiniteStateMachineToTypestateChangeFunction extends TypeStateMachineWeightFunctions {
private static final Logger LOGGER = LoggerFactory.getLogger(FiniteStateMachineToTypestateChangeFunction.class);
private RefType analyzedType = null;
private SootBasedStateMachineGraph fsm;
public FiniteStateMachineToTypestateChangeFunction(SootBasedStateMachineGraph fsm) {
for(MatcherTransition trans : fsm.getAllTransitions()){
this.addTransition(trans);
}
for(SootMethod m : fsm.initialTransitonLabel()){
if(m.isConstructor()){
if (analyzedType == null){
analyzedType = m.getDeclaringClass().getType();
} else {
// This code was added to detect unidentified outlying cases affected by the changes made for issue #47.
if (analyzedType != m.getDeclaringClass().getType()){
LOGGER.error("The type of m.getDeclaringClass() does not appear to be consistent across fsm.initialTransitonLabel().");
}
}
}
}
this.fsm = fsm;
}
@Override
public Collection<WeightedForwardQuery<TransitionFunction>> generateSeed(SootMethod method, Unit unit) {
Set<WeightedForwardQuery<TransitionFunction>> out = new HashSet<>();
if (!(unit instanceof Stmt) || !((Stmt) unit).containsInvokeExpr())
return out;
InvokeExpr invokeExpr = ((Stmt) unit).getInvokeExpr();
SootMethod calledMethod = invokeExpr.getMethod();
if (!fsm.initialTransitonLabel().contains(calledMethod))
return out;
if (calledMethod.isStatic()) {
if(unit instanceof AssignStmt){
AssignStmt stmt = (AssignStmt) unit;
out.add(createQuery(stmt,method,new AllocVal(stmt.getLeftOp(), method, stmt.getRightOp(), new Statement(stmt,method))));
}
} else if (invokeExpr instanceof InstanceInvokeExpr){
InstanceInvokeExpr iie = (InstanceInvokeExpr) invokeExpr;
out.add(createQuery(unit,method,new AllocVal(iie.getBase(), method,iie, new Statement((Stmt) unit,method))));
}
return out;
}
private WeightedForwardQuery<TransitionFunction> createQuery(Unit unit, SootMethod method, AllocVal allocVal) {
return new WeightedForwardQuery<TransitionFunction>(new Statement((Stmt)unit,method), allocVal, fsm.getInitialWeight(new Statement((Stmt)unit,method)));
}
@Override
protected State initialState() {
throw new UnsupportedOperationException("This method should never be called.");
}
}
| 3,013 | 34.046512 | 154 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/LabeledMatcherTransition.java | package crypto.typestate;
import java.util.List;
import crypto.rules.CrySLMethod;
import typestate.finiteautomata.MatcherTransition;
import typestate.finiteautomata.State;
public class LabeledMatcherTransition extends MatcherTransition {
private final List<CrySLMethod> label;
public LabeledMatcherTransition(State from, List<CrySLMethod> label, Parameter param, State to, Type type) {
super(from, CrySLMethodToSootMethod.v().convert(label), param, to, type);
this.label = label;
}
public List<CrySLMethod> label(){
return label;
}
}
| 552 | 24.136364 | 109 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/ReportingErrorStateNode.java | package crypto.typestate;
import java.util.Collection;
import soot.SootMethod;
import typestate.finiteautomata.State;
public class ReportingErrorStateNode implements State {
private Collection<SootMethod> expectedCalls;
private boolean report;
public ReportingErrorStateNode(Collection<SootMethod> expectedCalls) {
this.expectedCalls = expectedCalls;
}
public Collection<SootMethod> getExpectedCalls() {
return expectedCalls;
}
@Override
public boolean isErrorState() {
return true;
}
@Override
public boolean isInitialState() {
return false;
}
@Override
public boolean isAccepting() {
return false;
}
public boolean isReport() {
return report;
}
@Override
public String toString() {
return "ERR";
}
@Override
public int hashCode() {
return this.getClass().hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof ReportingErrorStateNode;
}
}
| 927 | 16.185185 | 71 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/SootBasedStateMachineGraph.java | package crypto.typestate;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import boomerang.jimple.Statement;
import crypto.rules.CrySLMethod;
import crypto.rules.StateMachineGraph;
import crypto.rules.StateNode;
import crypto.rules.TransitionEdge;
import soot.SootMethod;
import typestate.TransitionFunction;
import typestate.finiteautomata.MatcherTransition;
import typestate.finiteautomata.MatcherTransition.Parameter;
import typestate.finiteautomata.MatcherTransition.Type;
import typestate.finiteautomata.State;
public class SootBasedStateMachineGraph {
private Set<MatcherTransition> transition = new HashSet<>();
private Collection<SootMethod> edgeLabelMethods = Sets.newHashSet();
private final StateMachineGraph stateMachineGraph;
private Multimap<State, SootMethod> outTransitions = HashMultimap.create();
private Collection<SootMethod> initialTransitonLabel;
private List<CrySLMethod> crySLinitialTransitionLabel;
private LabeledMatcherTransition initialTransiton;
public SootBasedStateMachineGraph(StateMachineGraph fsm) {
this.stateMachineGraph = fsm;
//TODO #15 we must start the analysis in state stateMachineGraph.getInitialTransition().from();
for (final TransitionEdge t : stateMachineGraph.getAllTransitions()) {
WrappedState from = wrappedState(t.from());
WrappedState to = wrappedState(t.to());
LabeledMatcherTransition trans = new LabeledMatcherTransition(from, t.getLabel(),
Parameter.This, to, Type.OnCallOrOnCallToReturn);
this.addTransition(trans);
outTransitions.putAll(from, convert(t.getLabel()));
if(stateMachineGraph.getInitialTransition().equals(t))
this.initialTransiton = trans;
}
crySLinitialTransitionLabel = stateMachineGraph.getInitialTransition().getLabel();
initialTransitonLabel = convert(stateMachineGraph.getInitialTransition().getLabel());
//All transitions that are not in the state machine
for(StateNode t : this.stateMachineGraph.getNodes()){
State wrapped = wrappedState(t);
Collection<SootMethod> remaining = getInvolvedMethods();
Collection<SootMethod> expected = this.outTransitions.get(wrapped);
if(expected != null){
remaining.removeAll(expected);
ReportingErrorStateNode repErrorState = new ReportingErrorStateNode(expected);
this.addTransition(new MatcherTransition(wrapped, remaining, Parameter.This, new ReportingErrorStateNode(expected), Type.OnCallOrOnCallToReturn));
//Once an object is in error state, it always remains in the error state.
ErrorStateNode errorState = new ErrorStateNode();
this.addTransition(new MatcherTransition(repErrorState, getInvolvedMethods(), Parameter.This, errorState, Type.OnCallOrOnCallToReturn));
}
}
}
private WrappedState wrappedState(StateNode t) {
return new WrappedState(t, stateMachineGraph.getInitialTransition().from().equals(t));
}
public Collection<SootMethod> getEdgesOutOf(State n){
return outTransitions.get(n);
}
public void addTransition(MatcherTransition trans) {
transition.add(trans);
}
private Collection<SootMethod> convert(List<CrySLMethod> label) {
Collection<SootMethod> converted = CrySLMethodToSootMethod.v().convert(label);
edgeLabelMethods.addAll(converted);
return converted;
}
public Collection<SootMethod> getInvolvedMethods(){
return Sets.newHashSet(edgeLabelMethods);
}
public TransitionFunction getInitialWeight(Statement stmt) {
return new TransitionFunction(initialTransiton,Collections.singleton(stmt));
}
public List<MatcherTransition> getAllTransitions() {
return Lists.newArrayList(transition);
}
public Collection<SootMethod> initialTransitonLabel() {
return Lists.newArrayList(initialTransitonLabel);
}
public List<CrySLMethod> getInitialTransition() {
return crySLinitialTransitionLabel;
}
}
| 4,042 | 34.464912 | 150 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/typestate/WrappedState.java | package crypto.typestate;
import crypto.rules.StateNode;
import typestate.finiteautomata.State;
public class WrappedState implements State {
private final StateNode delegate;
private final boolean initialState;
WrappedState(StateNode delegate, boolean initialState) {
this.delegate = delegate;
this.initialState = initialState;
}
public WrappedState(StateNode delegate) {
this.delegate = delegate;
this.initialState = false;
}
public StateNode delegate(){
return delegate;
}
@Override
public boolean isErrorState() {
return delegate.isErrorState();
}
@Override
public boolean isAccepting() {
return delegate.getAccepting();
}
@Override
public boolean isInitialState() {
return initialState;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((delegate == null) ? 0 : delegate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WrappedState other = (WrappedState) obj;
if (delegate == null) {
if (other.delegate != null)
return false;
} else if (!delegate.equals(other.delegate))
return false;
return true;
}
@Override
public String toString() {
return delegate.getName().toString();
}
}
| 1,369 | 18.855072 | 75 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/IDEALCrossingTestingFramework.java | package test;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import boomerang.WeightedForwardQuery;
import boomerang.callgraph.ObservableDynamicICFG;
import boomerang.callgraph.ObservableICFG;
import boomerang.debugger.Debugger;
import boomerang.debugger.IDEVizDebugger;
import boomerang.jimple.Val;
import boomerang.preanalysis.BoomerangPretransformer;
import boomerang.results.ForwardBoomerangResults;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.CrySLResultsReporter;
import crypto.analysis.CrySLRulesetSelector;
import crypto.analysis.CrySLRulesetSelector.RuleFormat;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import crypto.exceptions.CryptoAnalysisException;
import crypto.rules.CrySLRule;
import crypto.typestate.CrySLMethodToSootMethod;
import crypto.typestate.ExtendedIDEALAnaylsis;
import crypto.typestate.SootBasedStateMachineGraph;
import ideal.IDEALSeedSolver;
import soot.Body;
import soot.Local;
import soot.SceneTransformer;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
import test.assertions.MustBeInState;
import test.core.selfrunning.AbstractTestingFramework;
import test.core.selfrunning.ImprecisionException;
import typestate.TransitionFunction;
public abstract class IDEALCrossingTestingFramework extends AbstractTestingFramework{
private static final Logger LOGGER = LoggerFactory.getLogger(IDEALCrossingTestingFramework.class);
protected JimpleBasedInterproceduralCFG staticIcfg;
protected ObservableICFG<Unit, SootMethod> icfg;
protected long analysisTime;
private Debugger<TransitionFunction> debugger;
public static final String RULES_BASE_DIR = "src/main/resources/";
private static final RuleFormat ruleFormat = RuleFormat.SOURCE;
protected ExtendedIDEALAnaylsis createAnalysis() {
return new ExtendedIDEALAnaylsis() {
@Override
protected ObservableICFG<Unit, SootMethod> icfg() {
return icfg;
}
@Override
public SootBasedStateMachineGraph getStateMachine() {
return new SootBasedStateMachineGraph(getRule().getUsagePattern());
}
@Override
public CrySLResultsReporter analysisListener() {
return null;
}
@Override
protected Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver) {
return getDebugger();
}
};
}
protected CrySLRule getRule() {
try {
return CrySLRulesetSelector.makeSingleRule(RULES_BASE_DIR, ruleFormat, getRuleset(), getRulename());
} catch (CryptoAnalysisException e) {
LOGGER.error("Error happened when getting the CrySL rules from the specified directory: "+RULES_BASE_DIR, e);
}
return null;
}
protected abstract String getRulename();
protected abstract Ruleset getRuleset();
@Override
public List<String> excludedPackages() {
List<String> excludedPackages = super.excludedPackages();
excludedPackages.add(getRule().getClassName());
return excludedPackages;
}
protected Debugger<TransitionFunction> getDebugger() {
if(debugger == null)
debugger = new IDEVizDebugger<>(ideVizFile, icfg);
return debugger;
}
@Override
protected SceneTransformer createAnalysisTransformer() throws ImprecisionException {
return new SceneTransformer() {
protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
BoomerangPretransformer.v().reset();
BoomerangPretransformer.v().apply();
staticIcfg = new JimpleBasedInterproceduralCFG(true);
// icfg = new ObservableStaticICFG(new JimpleBasedInterproceduralCFG(true));
icfg = new ObservableDynamicICFG(true);
Set<Assertion> expectedResults = parseExpectedQueryResults(sootTestMethod);
TestingResultReporter testingResultReporter = new TestingResultReporter(expectedResults);
Map<WeightedForwardQuery<TransitionFunction>, ForwardBoomerangResults<TransitionFunction>> seedToSolvers = executeAnalysis();
for(WeightedForwardQuery<TransitionFunction> seed : seedToSolvers.keySet()){
ForwardBoomerangResults<TransitionFunction> res = seedToSolvers.get(seed);
testingResultReporter.onSeedFinished(seed.asNode(), res.asStatementValWeightTable());
}
List<Assertion> unsound = Lists.newLinkedList();
List<Assertion> imprecise = Lists.newLinkedList();
for (Assertion r : expectedResults) {
if (!r.isSatisfied()) {
unsound.add(r);
}
}
for (Assertion r : expectedResults) {
if (r.isImprecise()) {
imprecise.add(r);
}
}
if (!unsound.isEmpty())
throw new RuntimeException("Unsound results: " + unsound);
if (!imprecise.isEmpty()) {
throw new ImprecisionException("Imprecise results: " + imprecise);
}
}
};
}
protected Map<WeightedForwardQuery<TransitionFunction>, ForwardBoomerangResults<TransitionFunction>> executeAnalysis() {
CrySLMethodToSootMethod.reset();
ExtendedIDEALAnaylsis analysis = IDEALCrossingTestingFramework.this.createAnalysis();
return analysis.run();
}
private Set<Assertion> parseExpectedQueryResults(SootMethod sootTestMethod) {
Set<Assertion> results = new HashSet<>();
parseExpectedQueryResults(sootTestMethod, results, new HashSet<SootMethod>());
return results;
}
private void parseExpectedQueryResults(SootMethod m, Set<Assertion> queries, Set<SootMethod> visited) {
if (!m.hasActiveBody() || visited.contains(m))
return;
visited.add(m);
Body activeBody = m.getActiveBody();
for (Unit callSite : staticIcfg.getCallsFromWithin(m)) {
for (SootMethod callee : staticIcfg.getCalleesOfCallAt(callSite))
parseExpectedQueryResults(callee, queries, visited);
}
for (Unit u : activeBody.getUnits()) {
if (!(u instanceof Stmt))
continue;
Stmt stmt = (Stmt) u;
if (!(stmt.containsInvokeExpr()))
continue;
InvokeExpr invokeExpr = stmt.getInvokeExpr();
String invocationName = invokeExpr.getMethod().getName();
if (!invocationName.startsWith("assertState"))
continue;
Value param = invokeExpr.getArg(0);
if (!(param instanceof Local))
continue;
Local queryVar = (Local) param;
Value param2 = invokeExpr.getArg(1);
Val val = new Val(queryVar, m);
queries.add(new MustBeInState(stmt, val, param2.toString()));
}
}
/**
* This method can be used in test cases to create branching. It is not
* optimized away.
*
* @return
*/
protected boolean staticallyUnknown() {
return true;
}
}
| 6,617 | 32.593909 | 129 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/TestingResultReporter.java | package test;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import soot.Unit;
import sync.pds.solver.nodes.Node;
import typestate.TransitionFunction;
import typestate.finiteautomata.ITransition;
import typestate.finiteautomata.State;
public class TestingResultReporter {
private Multimap<Unit, ComparableResult<State, Val>> allExpectedTypestateResults = HashMultimap.create();
public TestingResultReporter(Set<Assertion> expectedResults) {
for (Assertion e : expectedResults) {
if (e instanceof ComparableResult)
allExpectedTypestateResults.put(((ComparableResult<State, Val>) e).getStmt(),
(ComparableResult<State, Val>) e);
}
}
public void onSeedFinished(Node<Statement, Val> seed, final Table<Statement, Val, TransitionFunction> res) {
for (final Entry<Unit, ComparableResult<State, Val>> expectedResults : allExpectedTypestateResults.entries()) {
for (Cell<Statement, Val, TransitionFunction> s : res.cellSet()) {
Unit expectedUnit = expectedResults.getKey();
Val expectedVal = expectedResults.getValue().getVal();
Unit analysisResultUnit = s.getRowKey().getUnit().get();
Val analysisResultFact = s.getColumnKey();
if (analysisResultUnit.equals(expectedUnit) && analysisResultFact.equals(expectedVal)) {
for (ITransition trans : s.getValue().values()) {
if (trans.from() == null || trans.to() == null)
continue;
if (trans.from().isInitialState()) {
expectedResults.getValue().computedResults(trans.to());
}
}
}
}
}
}
}
| 1,772 | 33.096154 | 113 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/UsagePatternTestingFramework.java | package test;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import boomerang.BackwardQuery;
import boomerang.Query;
import boomerang.callgraph.ObservableDynamicICFG;
import boomerang.callgraph.ObservableICFG;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.preanalysis.BoomerangPretransformer;
import boomerang.results.ForwardBoomerangResults;
import crypto.analysis.AnalysisSeedWithSpecification;
import crypto.analysis.CrySLAnalysisListener;
import crypto.analysis.CrySLResultsReporter;
import crypto.analysis.CrySLRulesetSelector;
import crypto.analysis.CrySLRulesetSelector.RuleFormat;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import crypto.analysis.CryptoScanner;
import crypto.analysis.EnsuredCrySLPredicate;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.errors.AbstractError;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.ErrorVisitor;
import crypto.analysis.errors.ForbiddenMethodError;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.ImpreciseValueExtractionError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.NeverTypeOfError;
import crypto.analysis.errors.PredicateContradictionError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
import crypto.exceptions.CryptoAnalysisException;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.extractparameter.ExtractedValue;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLRule;
import soot.Body;
import soot.Local;
import soot.SceneTransformer;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
import sync.pds.solver.nodes.Node;
import test.assertions.Assertions;
import test.assertions.CallToForbiddenMethodAssertion;
import test.assertions.ConstraintErrorCountAssertion;
import test.assertions.ExtractedValueAssertion;
import test.assertions.HasEnsuredPredicateAssertion;
import test.assertions.InAcceptingStateAssertion;
import test.assertions.MissingTypestateChange;
import test.assertions.NoMissingTypestateChange;
import test.assertions.NotHasEnsuredPredicateAssertion;
import test.assertions.NotInAcceptingStateAssertion;
import test.assertions.PredicateContradiction;
import test.assertions.PredicateErrorCountAssertion;
import test.assertions.TypestateErrorCountAssertion;
import test.core.selfrunning.AbstractTestingFramework;
import test.core.selfrunning.ImprecisionException;
import typestate.TransitionFunction;
public abstract class UsagePatternTestingFramework extends AbstractTestingFramework{
protected ObservableICFG<Unit, SootMethod> icfg;
private JimpleBasedInterproceduralCFG staticIcfg;
private static final RuleFormat ruleFormat= RuleFormat.SOURCE;
List<CrySLRule> rules;
@Override
protected SceneTransformer createAnalysisTransformer() throws ImprecisionException {
return new SceneTransformer() {
protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
BoomerangPretransformer.v().reset();
BoomerangPretransformer.v().apply();
staticIcfg = new JimpleBasedInterproceduralCFG(true);
// icfg = new ObservableStaticICFG(new JimpleBasedInterproceduralCFG(true));
icfg = new ObservableDynamicICFG(true);
final Set<Assertion> expectedResults = extractBenchmarkMethods(sootTestMethod);
final TestingResultReporter resultReporter = new TestingResultReporter(expectedResults);
CryptoScanner scanner = new CryptoScanner() {
@Override
public ObservableICFG<Unit, SootMethod> icfg() {
return icfg;
}
@Override
public CrySLResultsReporter getAnalysisListener() {
CrySLAnalysisListener cryslListener = new CrySLAnalysisListener() {
@Override
public void onSeedFinished(IAnalysisSeed seed,
ForwardBoomerangResults<TransitionFunction> res) {
resultReporter.onSeedFinished(seed.asNode(), res.asStatementValWeightTable());
}
@Override
public void collectedValues(AnalysisSeedWithSpecification seed,
Multimap<CallSiteWithParamIndex, ExtractedValue> collectedValues) {
for(Assertion a : expectedResults){
if(a instanceof ExtractedValueAssertion){
((ExtractedValueAssertion) a).computedValues(collectedValues);
}
}
}
@Override
public void reportError(AbstractError error) {
error.accept(new ErrorVisitor() {
@Override
public void visit(RequiredPredicateError predicateError) {
for(Assertion a: expectedResults){
if(a instanceof PredicateErrorCountAssertion){
PredicateErrorCountAssertion errorCountAssertion = (PredicateErrorCountAssertion) a;
errorCountAssertion.increaseCount();
}
}
}
@Override
public void visit(TypestateError typestateError) {
for(Assertion a: expectedResults){
if(a instanceof TypestateErrorCountAssertion){
TypestateErrorCountAssertion errorCountAssertion = (TypestateErrorCountAssertion) a;
errorCountAssertion.increaseCount();
}
}
}
@Override
public void visit(IncompleteOperationError incompleteOperationError) {
boolean hasTypestateChangeError = false;
boolean expectsTypestateChangeError = false;
for(Assertion a: expectedResults){
if(a instanceof MissingTypestateChange){
MissingTypestateChange missingTypestateChange = (MissingTypestateChange) a;
if(missingTypestateChange.getStmt().equals(incompleteOperationError.getErrorLocation().getUnit().get())){
missingTypestateChange.trigger();
hasTypestateChangeError = true;
}
expectsTypestateChangeError = true;
}
if(a instanceof NoMissingTypestateChange){
throw new RuntimeException("Reports a typestate error that should not be reported");
}
}
if(hasTypestateChangeError != expectsTypestateChangeError){
throw new RuntimeException("Reports a typestate error that should not be reported");
}
}
@Override
public void visit(ForbiddenMethodError abstractError) {
for(Assertion e : expectedResults){
if(e instanceof CallToForbiddenMethodAssertion){
CallToForbiddenMethodAssertion expectedResults = (CallToForbiddenMethodAssertion) e;
expectedResults.reported(abstractError.getErrorLocation().getUnit().get());
}
}
}
@Override
public void visit(ConstraintError constraintError) {
for(Assertion a: expectedResults){
if(a instanceof ConstraintErrorCountAssertion){
ConstraintErrorCountAssertion errorCountAssertion = (ConstraintErrorCountAssertion) a;
errorCountAssertion.increaseCount();
}
}
}
@Override
public void visit(ImpreciseValueExtractionError predicateError) {
}
@Override
public void visit(NeverTypeOfError predicateError) {
// TODO Auto-generated method stub
}
@Override
public void visit(PredicateContradictionError predicateContradictionError) {
for (Assertion e : expectedResults) {
if (e instanceof PredicateContradiction) {
PredicateContradiction p = (PredicateContradiction) e;
p.trigger();
}
}
}
@Override
public void visit(HardCodedError predicateError) {
}
});
}
@Override
public void discoveredSeed(IAnalysisSeed curr) {
}
@Override
public void ensuredPredicates(Table<Statement, Val, Set<EnsuredCrySLPredicate>> existingPredicates,
Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> expectedPredicates,
Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> missingPredicates) {
for(Cell<Statement, Val, Set<EnsuredCrySLPredicate>> c : existingPredicates.cellSet()){
for(Assertion e : expectedResults){
if(e instanceof HasEnsuredPredicateAssertion){
HasEnsuredPredicateAssertion assertion = (HasEnsuredPredicateAssertion) e;
if(assertion.getStmt().equals(c.getRowKey().getUnit().get())){
for(EnsuredCrySLPredicate pred : c.getValue()){
assertion.reported(c.getColumnKey(),pred);
}
}
}
if(e instanceof NotHasEnsuredPredicateAssertion){
NotHasEnsuredPredicateAssertion assertion = (NotHasEnsuredPredicateAssertion) e;
if(assertion.getStmt().equals(c.getRowKey().getUnit().get())){
for(EnsuredCrySLPredicate pred : c.getValue()){
assertion.reported(c.getColumnKey(),pred);
}
}
}
}
}
}
@Override
public void seedStarted(IAnalysisSeed analysisSeedWithSpecification) {
}
@Override
public void boomerangQueryStarted(Query seed, BackwardQuery q) {
}
@Override
public void boomerangQueryFinished(Query seed, BackwardQuery q) {
}
@Override
public void checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification,
Collection<ISLConstraint> relConstraints) {
}
@Override
public void beforeAnalysis() {
}
@Override
public void afterAnalysis() {
}
@Override
public void beforeConstraintCheck(
AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void afterConstraintCheck(
AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void beforePredicateCheck(
AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void afterPredicateCheck(
AnalysisSeedWithSpecification analysisSeedWithSpecification) {
}
@Override
public void onSeedTimeout(Node<Statement, Val> seed) {
}
@Override
public void onSecureObjectFound(IAnalysisSeed analysisObject) {
// TODO Auto-generated method stub
}
@Override
public void addProgress(int processedSeeds, int workListsize) {
// TODO Auto-generated method stub
}
};
CrySLResultsReporter reporters = new CrySLResultsReporter();
reporters.addReportListener(cryslListener);
return reporters;
}
};
scanner.scan(getRules());
List<Assertion> unsound = Lists.newLinkedList();
List<Assertion> imprecise = Lists.newLinkedList();
for (Assertion r : expectedResults) {
if (!r.isSatisfied()) {
unsound.add(r);
}
}
for (Assertion r : expectedResults) {
if (r.isImprecise()) {
imprecise.add(r);
}
}
if (!unsound.isEmpty())
throw new RuntimeException("Unsound results: \n" + Joiner.on("\n").join(unsound));
if (!imprecise.isEmpty()) {
throw new ImprecisionException("Imprecise results: " + Joiner.on("\n").join(imprecise));
}
}
};
}
private List<CrySLRule> getRules() {
if(rules == null) {
try {
rules = CrySLRulesetSelector.makeFromRuleset(IDEALCrossingTestingFramework.RULES_BASE_DIR, ruleFormat, getRuleSet());
} catch (CryptoAnalysisException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return rules;
}
@Override
public List<String> excludedPackages() {
List<String> excludedPackages = super.excludedPackages();
for(CrySLRule r : getRules()) {
excludedPackages.add(r.getClassName());
}
return excludedPackages;
}
protected abstract Ruleset getRuleSet();
private Set<Assertion> extractBenchmarkMethods(SootMethod sootTestMethod) {
Set<Assertion> results = new HashSet<>();
extractBenchmarkMethods(sootTestMethod, results, new HashSet<SootMethod>());
return results;
}
private void extractBenchmarkMethods(SootMethod m, Set<Assertion> queries, Set<SootMethod> visited) {
if (!m.hasActiveBody() || visited.contains(m))
return;
visited.add(m);
Body activeBody = m.getActiveBody();
for (Unit callSite : staticIcfg.getCallsFromWithin(m)) {
for (SootMethod callee : staticIcfg.getCalleesOfCallAt(callSite))
extractBenchmarkMethods(callee, queries, visited);
}
for (Unit u : activeBody.getUnits()) {
if (!(u instanceof Stmt))
continue;
Stmt stmt = (Stmt) u;
if (!(stmt.containsInvokeExpr()))
continue;
InvokeExpr invokeExpr = stmt.getInvokeExpr();
if (!invokeExpr.getMethod().getDeclaringClass().toString().equals(Assertions.class.getName()))
continue;
String invocationName = invokeExpr.getMethod().getName();
if(invocationName.startsWith("extValue")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof IntConstant))
continue;
IntConstant paramIndex = (IntConstant) param;
for(Unit pred : getPredecessorsNotBenchmark(stmt))
queries.add(new ExtractedValueAssertion(pred, paramIndex.value));
}
if(invocationName.startsWith("callToForbiddenMethod")){
for(Unit pred : getPredecessorsNotBenchmark(stmt))
queries.add(new CallToForbiddenMethodAssertion(pred));
}
if(invocationName.startsWith("mustBeInAcceptingState")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof Local))
continue;
Local queryVar = (Local) param;
Val val = new Val(queryVar,m);
queries.add(new InAcceptingStateAssertion(stmt, val));
}
// if (invocationName.startsWith("violatedConstraint")) {
// queries.add(new ConstraintViolationAssertion(stmt));
// }
if(invocationName.startsWith("hasEnsuredPredicate")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof Local))
continue;
Local queryVar = (Local) param;
Val val = new Val(queryVar, m);
queries.add(new HasEnsuredPredicateAssertion(stmt, val));
}
if(invocationName.startsWith("notHasEnsuredPredicate")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof Local))
continue;
Local queryVar = (Local) param;
Val val = new Val(queryVar, m);
queries.add(new NotHasEnsuredPredicateAssertion(stmt, val));
}
if(invocationName.startsWith("mustNotBeInAcceptingState")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof Local))
continue;
Local queryVar = (Local) param;
Val val = new Val(queryVar, m);
queries.add(new NotInAcceptingStateAssertion(stmt, val));
}
if(invocationName.startsWith("predicateContradiction")){
queries.add(new PredicateContradiction());
}
if(invocationName.startsWith("missingTypestateChange")){
for(Unit pred : getPredecessorsNotBenchmark(stmt))
queries.add(new MissingTypestateChange((Stmt) pred));
}
if(invocationName.startsWith("noMissingTypestateChange")){
for(Unit pred : getPredecessorsNotBenchmark(stmt))
queries.add(new NoMissingTypestateChange((Stmt) pred));
}
if(invocationName.startsWith("predicateErrors")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof IntConstant))
continue;
IntConstant queryVar = (IntConstant) param;
queries.add(new PredicateErrorCountAssertion(queryVar.value));
}
if(invocationName.startsWith("constraintErrors")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof IntConstant))
continue;
IntConstant queryVar = (IntConstant) param;
queries.add(new ConstraintErrorCountAssertion(queryVar.value));
}
if(invocationName.startsWith("typestateErrors")){
Value param = invokeExpr.getArg(0);
if (!(param instanceof IntConstant))
continue;
IntConstant queryVar = (IntConstant) param;
queries.add(new TypestateErrorCountAssertion(queryVar.value));
}
}
}
private Set<Unit> getPredecessorsNotBenchmark(Stmt stmt) {
Set<Unit> res = Sets.newHashSet();
Set<Unit> visited = Sets.newHashSet();
LinkedList<Unit> worklist = Lists.newLinkedList();
worklist.add(stmt);
while(!worklist.isEmpty()){
Unit curr = worklist.poll();
if(!visited.add(curr))
continue;
if(!curr.toString().contains(Assertions.class.getSimpleName()) && (curr instanceof Stmt) && ((Stmt) curr).containsInvokeExpr()){
res.add(curr);
continue;
}
worklist.addAll(icfg.getPredsOf(curr));
}
return res;
}
}
| 17,388 | 32.896686 | 131 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/Assertions.java | package test.assertions;
public class Assertions {
public static void assertState(Object o, int state) {
}
public static void extValue(int pos) {
}
public static void assertValue(Object o, Object v) {
}
public static void mustNotBeInAcceptingState(Object o) {
}
public static void mustBeInAcceptingState(Object o) {
}
public static void violatedConstraint(Object o) {
}
public static void callToForbiddenMethod() {
}
public static void hasEnsuredPredicate(Object o) {
}
public static void notHasEnsuredPredicate(Object o){
}
public static void missingTypestateChange() {
}
public static void noMissingTypestateChange() {
}
public static void predicateContradiction() {
}
public static void predicateErrors(int i) {
}
public static void constraintErrors(int i) {
}
public static void typestateErrors(int i) {
}
}
| 908 | 13.66129 | 57 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/CallToForbiddenMethodAssertion.java | package test.assertions;
import soot.Unit;
import test.Assertion;
public class CallToForbiddenMethodAssertion implements Assertion {
private Unit stmt;
private boolean satisfied;
public CallToForbiddenMethodAssertion(Unit stmt) {
this.stmt = stmt;
}
@Override
public boolean isSatisfied() {
return satisfied;
}
@Override
public boolean isImprecise() {
return false;
}
@Override
public String toString() {
return "Expected to report a call to a forbidden method at this statement: " + stmt;
}
public void reported(Unit callSite) {
satisfied |= callSite.equals(stmt);
}
}
| 603 | 16.764706 | 86 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/ConstraintErrorCountAssertion.java | package test.assertions;
import test.Assertion;
public class ConstraintErrorCountAssertion implements Assertion {
private int expectedErrorCounts;
private int actualErrorCounts;
public ConstraintErrorCountAssertion(int numberOfCounts) {
this.expectedErrorCounts = numberOfCounts;
}
public void increaseCount(){
actualErrorCounts++;
}
@Override
public boolean isSatisfied() {
return expectedErrorCounts <= actualErrorCounts;
}
@Override
public boolean isImprecise() {
return expectedErrorCounts != actualErrorCounts;
}
}
| 549 | 17.965517 | 65 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/ConstraintViolationAssertion.java | package test.assertions;
import soot.Unit;
import test.Assertion;
public class ConstraintViolationAssertion implements Assertion {
private Unit stmt;
private boolean satisfied;
public ConstraintViolationAssertion(Unit stmt) {
this.stmt = stmt;
}
@Override
public boolean isSatisfied() {
return satisfied;
}
@Override
public boolean isImprecise() {
return false;
}
@Override
public String toString() {
return "Expected to report that a constraint is broken at this statement: " + this.stmt;
}
public void reported(Unit callSite) {
satisfied |= callSite.equals(stmt);
}
}
| 605 | 16.314286 | 90 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/ExtractedValueAssertion.java | package test.assertions;
import java.util.Map.Entry;
import com.google.common.collect.Multimap;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.extractparameter.ExtractedValue;
import soot.Unit;
import test.Assertion;
public class ExtractedValueAssertion implements Assertion {
private Unit stmt;
private int index;
private boolean satisfied;
public ExtractedValueAssertion(Unit stmt, int index) {
this.stmt = stmt;
this.index = index;
}
public void computedValues(Multimap<CallSiteWithParamIndex, ExtractedValue> collectedValues){
for(Entry<CallSiteWithParamIndex, ExtractedValue> e: collectedValues.entries()){
if(e.getKey().stmt().getUnit().get().equals(stmt) && e.getKey().getIndex() == index)
satisfied = true;
}
}
@Override
public boolean isSatisfied() {
return satisfied;
}
@Override
public boolean isImprecise() {
return false;
}
@Override
public String toString() {
return "Did not extract parameter with index: " + index + " @ " + stmt;
}
}
| 1,018 | 23.261905 | 94 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/HasEnsuredPredicateAssertion.java | package test.assertions;
import boomerang.jimple.Val;
import crypto.analysis.EnsuredCrySLPredicate;
import soot.jimple.Stmt;
import test.Assertion;
public class HasEnsuredPredicateAssertion implements Assertion {
private Stmt stmt;
private Val val;
private boolean satisfied;
public HasEnsuredPredicateAssertion(Stmt stmt, Val val) {
this.stmt = stmt;
this.val = val;
}
public Val getAccessGraph() {
return val;
}
@Override
public boolean isSatisfied() {
return satisfied;
}
@Override
public boolean isImprecise() {
return false;
}
public Stmt getStmt() {
return stmt;
}
public void reported(Val seed, EnsuredCrySLPredicate pred) {
if(seed.equals(val))
satisfied = true;
}
@Override
public String toString() {
return "Expected a predicate for "+ val +" @ " + stmt;
}
}
| 823 | 16.166667 | 64 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/InAcceptingStateAssertion.java | package test.assertions;
import boomerang.jimple.Val;
import soot.Unit;
import test.Assertion;
import test.ComparableResult;
import typestate.finiteautomata.State;
public class InAcceptingStateAssertion implements Assertion, ComparableResult<State,Val> {
private Unit unit;
private Val val;
private boolean satisfied;
public InAcceptingStateAssertion(Unit unit, Val val) {
this.unit = unit;
this.val = val;
}
public void computedResults(State s) {
satisfied |= s.isAccepting();
}
public Unit getStmt() {
return unit;
}
@Override
public boolean isSatisfied() {
return satisfied;
}
@Override
public boolean isImprecise() {
return false;
}
@Override
public String toString() {
return "[" + getVal() + "@" + getStmt() + " must not be in error state]";
}
@Override
public Val getVal() {
return val;
}
}
| 845 | 16.625 | 90 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/MissingTypestateChange.java | package test.assertions;
import soot.Unit;
import soot.jimple.Stmt;
import test.Assertion;
/**
* Created by johannesspath on 24.12.17.
*/
public class MissingTypestateChange implements Assertion{
private final Stmt stmt;
private int triggered;
public MissingTypestateChange(Stmt stmt) {
this.stmt = stmt;
}
@Override
public boolean isSatisfied() {
return triggered > 0;
}
@Override
public boolean isImprecise() {
return triggered != 1;
}
@Override
public String toString() {
return "Expected a missing typestate change @ " + stmt;
}
public Unit getStmt() {
return stmt;
}
public void trigger(){
triggered++;
}
}
| 712 | 16.390244 | 63 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/MustBeInState.java | package test.assertions;
import boomerang.jimple.Val;
import crypto.typestate.ReportingErrorStateNode;
import soot.Unit;
import test.Assertion;
import test.ComparableResult;
import typestate.finiteautomata.State;
public class MustBeInState implements Assertion, ComparableResult<State,Val> {
private Unit unit;
private Val accessGraph;
private String state;
private boolean satisfied;
private int imprecise;
public MustBeInState(Unit unit, Val accessGraph, String state) {
this.unit = unit;
this.accessGraph = accessGraph;
this.state = state;
}
public void computedResults(State s) {
if ((state.toString().equals("-1") && s instanceof ReportingErrorStateNode) || state.toString().equals(s.toString())) {
satisfied |= true;
imprecise++;
}
}
public Unit getStmt() {
return unit;
}
@Override
public boolean isSatisfied() {
return satisfied;
}
@Override
public boolean isImprecise() {
return imprecise > 1;
}
public Val getVal() {
return accessGraph;
}
@Override
public String toString() {
return "["+getVal() + "@" + getStmt() + " must be in state "+ state+"]";
}
}
| 1,122 | 19.796296 | 121 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/NoMissingTypestateChange.java | package test.assertions;
import soot.Unit;
import soot.jimple.Stmt;
import test.Assertion;
/**
* Created by johannesspath on 24.12.17.
*/
public class NoMissingTypestateChange implements Assertion{
private final Stmt stmt;
public NoMissingTypestateChange(Stmt stmt) {
this.stmt = stmt;
}
@Override
public boolean isSatisfied() {
return true;
}
@Override
public boolean isImprecise() {
return false;
}
@Override
public String toString() {
return "Expected a missing typestate change @ " + stmt;
}
public Unit getStmt() {
return stmt;
}
}
| 630 | 16.527778 | 63 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/NotHasEnsuredPredicateAssertion.java | package test.assertions;
import boomerang.jimple.Val;
import crypto.analysis.EnsuredCrySLPredicate;
import soot.jimple.Stmt;
import test.Assertion;
public class NotHasEnsuredPredicateAssertion implements Assertion {
private Stmt stmt;
private Val val;
private boolean imprecise = false;
public NotHasEnsuredPredicateAssertion(Stmt stmt, Val val) {
this.stmt = stmt;
this.val = val;
}
public Val getAccessGraph() {
return val;
}
@Override
public boolean isSatisfied() {
return true;
}
@Override
public boolean isImprecise() {
return imprecise;
}
public Stmt getStmt() {
return stmt;
}
public void reported(Val value, EnsuredCrySLPredicate pred) {
if(value.equals(val)){
imprecise = true;
}
}
@Override
public String toString() {
return "Did not expect a predicate for "+ val +" @ " + stmt;
}
}
| 848 | 16.326531 | 67 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/NotInAcceptingStateAssertion.java | package test.assertions;
import boomerang.jimple.Val;
import soot.Unit;
import test.Assertion;
import test.ComparableResult;
import typestate.finiteautomata.State;
public class NotInAcceptingStateAssertion implements Assertion, ComparableResult<State,Val> {
private Unit unit;
private Val val;
private boolean satisfied;
public NotInAcceptingStateAssertion(Unit unit, Val accessGraph) {
this.unit = unit;
this.val = accessGraph;
}
public void computedResults(State s) {
satisfied |= !s.isAccepting();
}
public Unit getStmt() {
return unit;
}
@Override
public boolean isSatisfied() {
return satisfied;
}
@Override
public boolean isImprecise() {
return false;
}
@Override
public String toString() {
return "[" + getVal() + "@" + getStmt() + " must not be in error state]";
}
@Override
public Val getVal() {
return val;
}
}
| 868 | 17.104167 | 93 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/PredicateContradiction.java | package test.assertions;
import test.Assertion;
public class PredicateContradiction implements Assertion{
private boolean triggered;
@Override
public boolean isSatisfied() {
return triggered;
}
@Override
public boolean isImprecise() {
return false;
}
public void trigger(){
triggered = true;
}
}
| 317 | 12.826087 | 57 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/PredicateErrorCountAssertion.java | package test.assertions;
import test.Assertion;
public class PredicateErrorCountAssertion implements Assertion {
private int expectedErrorCounts;
private int actualErrorCounts;
public PredicateErrorCountAssertion(int numberOfCounts) {
this.expectedErrorCounts = numberOfCounts;
}
public void increaseCount(){
actualErrorCounts++;
}
@Override
public boolean isSatisfied() {
return expectedErrorCounts <= actualErrorCounts;
}
@Override
public boolean isImprecise() {
return expectedErrorCounts != actualErrorCounts;
}
}
| 547 | 17.896552 | 64 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/assertions/TypestateErrorCountAssertion.java | package test.assertions;
import test.Assertion;
public class TypestateErrorCountAssertion implements Assertion {
private int expectedErrorCounts;
private int actualErrorCounts;
public TypestateErrorCountAssertion(int numberOfCounts) {
this.expectedErrorCounts = numberOfCounts;
}
public void increaseCount(){
actualErrorCounts++;
}
@Override
public boolean isSatisfied() {
return expectedErrorCounts <= actualErrorCounts;
}
@Override
public boolean isImprecise() {
return expectedErrorCounts != actualErrorCounts;
}
}
| 547 | 17.896552 | 64 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/BufferedBlockCipherTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class BufferedBlockCipherTest extends FiniteStateMachineTestingFramework{
public BufferedBlockCipherTest() {
super("BufferedBlockCipher", Ruleset.BouncyCastle);
this.order = new Simple(new E("BufferedBlockCipher"), new Plus(new Simple(new E("init"), new E("processByte"), new E("doFinal"))));
}
// Cons, (Inits, Procs, DOFINALS)+
}
| 462 | 27.9375 | 133 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/CipherTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class CipherTest extends FiniteStateMachineTestingFramework{
public CipherTest() {
super("Cipher", Ruleset.JavaCryptographicArchitecture);
this.order = new Simple(new E("getInstance"), new Plus(new E("init")), new Or(new Plus(new E("wrap")), new Plus(new Or(new E("doFinal"), new Simple(new Plus(new E("update")), new E("doFinal"))))));
}
// Gets, Inits+, WKB+ | (FINWOU | (Updates+, DOFINALS))+
}
| 527 | 32 | 199 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/ECElGamalDecryptorTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class ECElGamalDecryptorTest extends FiniteStateMachineTestingFramework{
public ECElGamalDecryptorTest() {
super("ECElGamalDecryptor", Ruleset.BouncyCastle);
order = new Simple(new E("ECElGamalDecryptor"), new Plus(new Simple(new E("init"), new Plus(new E("decrypt")))));
}
// Cons, (Inits, Decrypts+)+
}
| 435 | 26.25 | 115 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/FiniteStateMachineTestingFramework.java | package test.finitestatemachine;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import crypto.analysis.CrySLRulesetSelector;
import crypto.analysis.CrySLRulesetSelector.RuleFormat;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import crypto.exceptions.CryptoAnalysisException;
import crypto.rules.StateMachineGraph;
import crypto.rules.StateNode;
import crypto.rules.TransitionEdge;
import org.junit.Before;
import test.IDEALCrossingTestingFramework;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
public abstract class FiniteStateMachineTestingFramework{
private StateMachineGraph smg;
private String crySLRule;
private Ruleset ruleset;
protected Order order;
protected static int maxRepeat;
public FiniteStateMachineTestingFramework(String crySLRule, Ruleset ruleset) {
this.crySLRule = crySLRule;
this.ruleset = ruleset;
}
// uncomment "@Test" to test the StatemachineBuilder.
// These tests require a lot of memory and runtime and are thus excluded to not run each time.
// Further, the tests solely test the StatemachineBuilder and thereby only require to be executed when changing the Builder.
//@Test
public void simulate() {
if(order != null) {
benchmark();
}
}
public void benchmark() {
// valid paths
maxRepeat = 1;
List<List<String>> allPossiblePathsMaxRepeat1 = order.get();
maxRepeat = 3;
List<List<String>> allPossiblePathsMaxRepeat3 = order.get();
for(List<String> path: allPossiblePathsMaxRepeat3) {
assertInSMG(path);
}
// invalid paths
assertRandomInvalidPaths(allPossiblePathsMaxRepeat1, allPossiblePathsMaxRepeat3);
}
public void assertRandomInvalidPaths(List<List<String>> pathsWithSmallRepeat, List<List<String>> pathsWithLargeRepeat) {
for(List<String> path: pathsWithSmallRepeat) {
if(path.size()>1) {
for(int i=0; i<10; i++) {
List<String> events = Lists.newArrayList(path);
switch((new Random()).nextInt(2)){
case 0:
// delete an event
int rand = (new Random()).nextInt(events.size());
events.remove(rand);
break;
case 1:
// switch two events
int rand1 = (new Random()).nextInt(events.size());
String event = events.remove(rand1);
int rand2 = (new Random()).nextInt(events.size());
events.add(rand2, event);
break;
}
if(!pathsWithLargeRepeat.contains(events)) {
assertNotInSMG(events);
}
}
}
}
}
public void assertInSMG(List<String> methodPath) {
if(!isPathOfMethodsInSMG(methodPath)) {
throw new AssertionError("Order of calls are not in SMG but should be: " + methodPath.toString());
};
}
public void assertNotInSMG(List<String> methodPath) {
if(!methodPath.isEmpty() && isPathOfMethodsInSMG(methodPath)) {
// the initial state is always accepting.
throw new AssertionError("Order of calls are in SMG but should probably not be: " + methodPath.toString());
};
}
private boolean isPathOfMethodsInSMG(List<String> methodPath) {
final Set<StateNode> current = Sets.newHashSet();
current.add(smg.getInitialTransition().getLeft());
for(String event: methodPath) {
List<TransitionEdge> matchingEdges = smg.getAllTransitions().stream().filter(edge -> current.contains(edge.getLeft()) && edge.getLabel().stream().anyMatch(label -> label.getName().contains(event))).collect(Collectors.toList());
if(matchingEdges.size() == 0) {
// found no matching edge
return false;
}
current.clear();
matchingEdges.forEach(edge -> current.add(edge.getRight()));
}
return current.stream().anyMatch(node -> node.getAccepting());
}
@Before
public void createSMG() {
if(this.smg == null) {
try {
this.smg = CrySLRulesetSelector.makeSingleRule(IDEALCrossingTestingFramework.RULES_BASE_DIR, RuleFormat.SOURCE, this.ruleset, this.crySLRule).getUsagePattern();
} catch (CryptoAnalysisException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//
// Classes of type Order are able to generate all possible paths of events
// up to a certain recursion depth for * and +
//
public interface Order{
List<List<String>> get();
}
public class Simple implements Order{
private Order[] order;
public Simple(Order... order){
this.order = order;
}
public List<List<String>> get() {
List<List<String>> result = Lists.newArrayList();
result.add(Lists.newArrayList());
for(Order o: order) {
List<List<String>> possibleNextSteps = o.get();
List<List<String>> possiblePathesWithNextSteps = Lists.newArrayList();
for(List<String> possiblePathesUpToThisOrderIteration: result) {
for(List<String> nextSteps: possibleNextSteps) {
List<String> tmp = Lists.newArrayList(possiblePathesUpToThisOrderIteration);
tmp.addAll(nextSteps);
possiblePathesWithNextSteps.add(tmp);
}
}
result = possiblePathesWithNextSteps;
}
return result;
}
}
public class Or implements Order{
private Order[] order;
public Or(Order... order){
this.order = order;
}
public List<List<String>> get() {
List<List<String>> result = Lists.newArrayList();
for(Order o: order) {
result.addAll(o.get());
}
return result;
}
}
public static class Plus implements Order{
private Order order;
public Plus(Order order){
this.order = order;
}
public List<List<String>> get() {
List<List<String>> result = Lists.newArrayList();
result.add(Lists.newArrayList());
for(int i=0; i<FiniteStateMachineTestingFramework.maxRepeat; i++) {
List<List<String>> newPathes = Lists.newArrayList();
for(List<String> possibleStartPaths: result) {
for(List<String> possibleRepeats: order.get()) {
List<String> clone = Lists.newArrayList(possibleStartPaths);
clone.addAll(possibleRepeats);
newPathes.add(clone);
}
}
result.addAll(newPathes);
}
result.remove(0); // empty path should not be in result
return result;
}
}
public class Opt implements Order{
private Order order;
public Opt(Order order){
this.order = order;
}
public List<List<String>> get() {
List<List<String>> result = Lists.newArrayList();
result.add(Lists.newArrayList());
result.addAll(order.get());
return result;
}
}
public class Star implements Order{
private Order order;
public Star(Order order){
this.order = new Opt(new Plus(order));
}
public List<List<String>> get() {
return order.get();
}
}
public class E implements Order{
private String event;
public E(String event){
this.event = event;
}
public List<List<String>> get() {
List<List<String>> result = Lists.newArrayList();
result.add(Lists.newArrayList(event));
return result;
}
}
}
| 6,854 | 27.094262 | 230 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/HMacTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class HMacTest extends FiniteStateMachineTestingFramework{
public HMacTest() {
super("HMac", Ruleset.BouncyCastle);
this.order = new Simple(new E("HMac"), new Plus(new Simple(new E("init"), new Plus(new E("update")), new E("doFinal"))));
}
// Cons, (Init, Updates+, Finals)+
}
| 405 | 24.375 | 123 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/KeyFactoryTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class KeyFactoryTest extends FiniteStateMachineTestingFramework{
public KeyFactoryTest() {
super("KeyFactory", Ruleset.JavaCryptographicArchitecture);
this.order = new Simple(new E("getInstance"), new Star(new Or(new Star(new E("generatePrivate")), new Star(new E("generatePublic")))));
}
// Gets, (GenPriv* | GenPubl*)*
}
| 452 | 27.3125 | 137 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/KeyStoreTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class KeyStoreTest extends FiniteStateMachineTestingFramework{
public KeyStoreTest() {
super("KeyStore", Ruleset.JavaCryptographicArchitecture);
this.order = new Simple(new E("getInstance"), new E("load"),
new Star(new Or(new Simple(new Opt(new E("getEntry")), new E("getKey")),
new Simple(new E("setEntry"), new E("store")))));
}
// Gets, Loads, ((GetEntry?, GetKey) | (SetEntry, Stores))*
}
| 535 | 27.210526 | 77 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/MessageDigestTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class MessageDigestTest extends FiniteStateMachineTestingFramework{
public MessageDigestTest() {
super("MessageDigest", Ruleset.JavaCryptographicArchitecture);
this.order = new Simple(new E("getInstance"), new Plus(new Or(new E("digest"), new Simple(new Plus(new E("update")), new E("digest")))));
}
// Gets, (DWOU | (Updates+, Digests))+
}
| 470 | 28.4375 | 139 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/SHA256DigestTest.java | package test.finitestatemachine;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class SHA256DigestTest extends FiniteStateMachineTestingFramework{
public SHA256DigestTest() {
super("SHA256Digest", Ruleset.BouncyCastle);
this.order = new Simple(new E("SHA256Digest"), new Star(new Simple(new Plus(new E("update")), new E("doFinal"))));
}
// Cons, (Updates+, Finals)*
}
| 397 | 23.875 | 116 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/SSLEngineTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class SSLEngineTest extends FiniteStateMachineTestingFramework{
public SSLEngineTest() {
super("SSLEngine", Ruleset.JavaCryptographicArchitecture);
this.order = new Or(new Simple(new E("setEnabledCipherSuites"), new E("setEnabledProtocols")), new Simple(new E("setEnabledProtocols"), new E("setEnabledCipherSuites")));
}
// (EnableCipher, EnableProtocol) | (EnableProtocol, EnableCipher)
}
| 520 | 31.5625 | 172 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/SecretKey.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class SecretKey extends FiniteStateMachineTestingFramework{
public SecretKey() {
super("SecretKey", Ruleset.JavaCryptographicArchitecture);
this.order = new Simple(new Star(new E("getEncoded")), new Opt(new E("destroy")));
}
// GetEnc*, Destroy?
}
| 377 | 22.625 | 84 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/SecureRandom.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class SecureRandom extends FiniteStateMachineTestingFramework{
public SecureRandom() {
super("SecureRandom", Ruleset.JavaCryptographicArchitecture);
this.order = new Simple(new E("getInstance"), new Star(new Simple(new Opt(new E("setSeed")), new Star(new E("generateSeed")))));
}
// Ins, (Seeds?, Ends*)*
}
| 440 | 23.5 | 130 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/test/finitestatemachine/SignatureTest.java | package test.finitestatemachine;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
public class SignatureTest extends FiniteStateMachineTestingFramework{
public SignatureTest() {
super("Signature", Ruleset.JavaCryptographicArchitecture);
this.order = new Simple(new E("getInstance"),
new Or(
new Simple(new Plus(new E("initSign")), new Plus(new Simple(new Plus( new E("update")), new Plus(new E("sign"))))),
new Simple(new Plus(new E("initVerify")), new Plus(new Simple(new Star( new E("update")), new Plus(new E("verify")))))
)
);
}
// THIS HAS TO MANY REPEATITIONS
// The Test framework is not able to generate all possible paths for the following
// Gets, ((InitSigns+, (Updates+, Signs+)+ )+ | (InitVerifies+, (Updates*, Verifies+)+ )+ )
// We simplify it to
// Gets, ( InitSigns+, (Updates+, Signs+)+ | InitVerifies+, (Updates*, Verifies+)+ )
}
| 919 | 35.8 | 124 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/crysl/ZipCrySLTest.java | package tests.crysl;
import java.io.File;
import java.util.Collection;
import java.util.stream.Collectors;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import crypto.exceptions.CryptoAnalysisException;
import crypto.rules.CrySLRule;
import crypto.rules.CrySLRuleReader;
public class ZipCrySLTest
{
private static final String emptyZipFilePath = "src/test/resources/crySL/empty.zip";
private static final String jcaRulesetZipFilePath = "src/test/resources/crySL/JavaCryptographicArchitecture-1.5.1-ruleset.zip";
private static final String multipleRulesetZipFilePath = "src/test/resources/crySL/Multiple-rulesets.zip";
private static final String junkRuleSet = "src/test/resources/crySL/rulesetWithJunk.zip";
@Test(expected = CryptoAnalysisException.class)
public void TestJunkThrows() throws CryptoAnalysisException {
File zipFile = new File(junkRuleSet);
Collection<CrySLRule> rules = CrySLRuleReader.readFromZipFile(zipFile);
}
@Test
public void TestNumberOfRules() throws CryptoAnalysisException {
File zipFile = new File(jcaRulesetZipFilePath);
Collection<CrySLRule> rules = null;
rules = CrySLRuleReader.readFromZipFile(zipFile);
Assert.assertEquals(46, rules.size());
}
@Test
public void TestRulesNotNull() throws CryptoAnalysisException {
File zipFile = new File(jcaRulesetZipFilePath);
Collection<CrySLRule> rules = CrySLRuleReader.readFromZipFile(zipFile);
Collection<CrySLRule> notNullRules = rules.stream().filter(x -> x != null).collect(Collectors.toList());
Assert.assertEquals(46, notNullRules.size());
}
@Test(expected = CryptoAnalysisException.class)
public void TestFileNotExists() throws CryptoAnalysisException {
File zipFile = new File("notExist");
Collection<CrySLRule> rules = CrySLRuleReader.readFromZipFile(zipFile);
Assert.assertEquals(0, rules.size());
}
@Test
public void TestFileNoCrypSLFiles() throws CryptoAnalysisException {
File zipFile = new File(emptyZipFilePath);
Collection<CrySLRule> rules = CrySLRuleReader.readFromZipFile(zipFile);
Assert.assertEquals(0, rules.size());
}
@Test
public void TestFileContainsMultipleRulesets() throws CryptoAnalysisException {
File zipFile = new File(multipleRulesetZipFilePath);
Collection<CrySLRule> rules = CrySLRuleReader.readFromZipFile(zipFile);
Assert.assertEquals(102, rules.size());
}
@Test
public void TestRunTwiceSameResult() throws CryptoAnalysisException {
File zipFile = new File(jcaRulesetZipFilePath);
Collection<CrySLRule> rules = CrySLRuleReader.readFromZipFile(zipFile);
Assert.assertEquals(46, rules.size());
rules = CrySLRuleReader.readFromZipFile(zipFile);
Assert.assertEquals(46, rules.size());
}
@Test
@Ignore
public void TestPerformanceReducesSignificantlySecondTime() throws CryptoAnalysisException {
File zipFile = new File(jcaRulesetZipFilePath);
StopWatch watch = new StopWatch();
watch.start();
CrySLRuleReader.readFromZipFile(zipFile);
watch.stop();
long firstRun = watch.getTime();
watch.reset();
watch.start();
CrySLRuleReader.readFromZipFile(zipFile);
watch.stop();
long secondRun = watch.getTime();
Assert.assertTrue(secondRun * 100 < firstRun);
System.out.println("First: " + firstRun + "; Second: " + secondRun);
}
} | 3,684 | 37.385417 | 131 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/endoflifecycle/EndOfLifeCycleErrorTest.java | package tests.endoflifecycle;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
/**
* Created by johannesspath on 24.12.17.
*/
public class EndOfLifeCycleErrorTest extends UsagePatternTestingFramework {
@Test
public void missingDoFinalCall() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.missingTypestateChange();
}
@Test
public void missingGerateKey() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
Assertions.missingTypestateChange();
}
@Test
public void missingGerateKeyCatched() {
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
Assertions.missingTypestateChange();
} catch (Exception e) {
}
}
@Test
public void missingDoFinalCall2() throws GeneralSecurityException, DestroyFailedException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.missingTypestateChange();
key.destroy();
}
@Test
public void missingDoFinalCall3() throws GeneralSecurityException, DestroyFailedException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Container con = new Container();
con.c = cCipher;
cCipher.init(Cipher.ENCRYPT_MODE, key);
Cipher cipher = con.c;
cipher.getAlgorithm();
Assertions.missingTypestateChange();
key.destroy();
}
@Test
public void missingDoFinalCall5() throws GeneralSecurityException, DestroyFailedException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Container con = new Container();
con.c = cCipher;
cCipher.init(Cipher.ENCRYPT_MODE, key);
Cipher cipher = con.c;
cipher.doFinal(null);
Assertions.noMissingTypestateChange();
cipher.getAlgorithm();
key.destroy();
}
private class Container {
Cipher c;
}
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
}
| 2,768 | 26.969697 | 92 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/forbiddenmethods/PBEKeySpecTest.java | package tests.forbiddenmethods;
import java.security.NoSuchAlgorithmException;
import javax.crypto.spec.PBEKeySpec;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class PBEKeySpecTest extends UsagePatternTestingFramework {
@Test
public void PBEKeySpecTest1() throws NoSuchAlgorithmException {
PBEKeySpec pbe = new PBEKeySpec(new char[]{});
Assertions.callToForbiddenMethod();
}
@Test
public void PBEKeySpecTest2() throws NoSuchAlgorithmException {
PBEKeySpec pbe = new PBEKeySpec(new char[]{}, new byte[1], 1000);
Assertions.callToForbiddenMethod();
}
@Test
public void PBEKeySpecTest3() throws NoSuchAlgorithmException {
PBEKeySpec pbe = new PBEKeySpec(new char[]{}, new byte[1], 1000);
Assertions.callToForbiddenMethod();
}
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
}
| 970 | 23.897436 | 67 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/AbstractHeadlessTest.java | package tests.headless;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import boomerang.BackwardQuery;
import boomerang.Query;
import boomerang.jimple.Statement;
import boomerang.jimple.Val;
import boomerang.results.ForwardBoomerangResults;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.AnalysisSeedWithSpecification;
import crypto.analysis.CrySLAnalysisListener;
import crypto.analysis.CrySLRulesetSelector;
import crypto.analysis.CrySLRulesetSelector.RuleFormat;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import crypto.analysis.CryptoScannerSettings.ReportFormat;
import crypto.analysis.EnsuredCrySLPredicate;
import crypto.analysis.IAnalysisSeed;
import crypto.analysis.errors.AbstractError;
import crypto.exceptions.CryptoAnalysisException;
import crypto.extractparameter.CallSiteWithParamIndex;
import crypto.extractparameter.ExtractedValue;
import crypto.interfaces.ISLConstraint;
import crypto.rules.CrySLPredicate;
import crypto.rules.CrySLRule;
import soot.G;
import sync.pds.solver.nodes.Node;
import test.IDEALCrossingTestingFramework;
import tests.headless.FindingsType.FalseNegatives;
import tests.headless.FindingsType.FalsePositives;
import tests.headless.FindingsType.NoFalseNegatives;
import tests.headless.FindingsType.NoFalsePositives;
import tests.headless.FindingsType.TruePositives;
import typestate.TransitionFunction;
public abstract class AbstractHeadlessTest {
/**
* To run these test cases in Eclipse, specify your maven home path as JVM argument: -Dmaven.home=<PATH_TO_MAVEN_BIN>
*/
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHeadlessTest.class);
private static final RuleFormat ruleFormat = RuleFormat.SOURCE;
private static boolean VISUALIZATION = false;
private static boolean PROVIDER_DETECTION = true;
private CrySLAnalysisListener errorCountingAnalysisListener;
private Table<String, Class<?>, Integer> errorMarkerCountPerErrorTypeAndMethod = HashBasedTable.create();
private static ReportFormat reportFormat = null;
public static void setReportFormat(ReportFormat reportFormat) {
AbstractHeadlessTest.reportFormat = reportFormat;
}
public static void setVISUALIZATION(boolean vISUALIZATION) {
VISUALIZATION = vISUALIZATION;
}
public static void setProviderDetection(boolean providerDetection) {
PROVIDER_DETECTION = providerDetection;
}
protected MavenProject createAndCompile(String mavenProjectPath) {
MavenProject mi = new MavenProject(mavenProjectPath);
mi.compile();
return mi;
}
protected HeadlessCryptoScanner createScanner(MavenProject mp) {
return createScanner(mp, Ruleset.JavaCryptographicArchitecture);
}
protected HeadlessCryptoScanner createScanner(MavenProject mp, Ruleset ruleset) {
G.v().reset();
HeadlessCryptoScanner scanner = new HeadlessCryptoScanner() {
@Override
protected String sootClassPath() {
return mp.getBuildDirectory() + (mp.getFullClassPath().equals("") ? "" : File.pathSeparator + mp.getFullClassPath());
}
@Override
protected List<CrySLRule> getRules() {
try {
List<CrySLRule> rules = Lists.newArrayList();
rules = CrySLRulesetSelector.makeFromRuleset(IDEALCrossingTestingFramework.RULES_BASE_DIR, ruleFormat, ruleset);
HeadlessCryptoScanner.setRules(rules);
return rules;
} catch (CryptoAnalysisException e) {
LOGGER.error("Error happened when getting the CrySL rules from the specified directory: "+IDEALCrossingTestingFramework.RULES_BASE_DIR, e);
}
return null;
}
@Override
protected String applicationClassPath() {
return mp.getBuildDirectory();
}
@Override
protected CrySLAnalysisListener getAdditionalListener() {
return errorCountingAnalysisListener;
}
@Override
protected String getOutputFolder() {
File file = new File("cognicrypt-output/");
file.mkdirs();
return VISUALIZATION ? file.getAbsolutePath() : super.getOutputFolder();
}
@Override
protected boolean enableVisualization() {
return VISUALIZATION;
}
@Override
protected boolean providerDetection() {
return PROVIDER_DETECTION;
}
@Override
protected ReportFormat reportFormat(){
return VISUALIZATION ? reportFormat : null;
}
};
return scanner;
}
@Before
public void setup() {
errorCountingAnalysisListener = new CrySLAnalysisListener() {
@Override
public void reportError(AbstractError error) {
Integer currCount;
String methodContainingError = error.getErrorLocation().getMethod().toString();
if (errorMarkerCountPerErrorTypeAndMethod.contains(methodContainingError, error.getClass())) {
currCount = errorMarkerCountPerErrorTypeAndMethod.get(methodContainingError, error.getClass());
} else {
currCount = 0;
}
Integer newCount = --currCount;
errorMarkerCountPerErrorTypeAndMethod.put(methodContainingError, error.getClass(), newCount);
}
@Override
public void onSeedTimeout(Node<Statement, Val> seed) {}
@Override
public void onSeedFinished(IAnalysisSeed seed, ForwardBoomerangResults<TransitionFunction> solver) {}
@Override
public void ensuredPredicates(Table<Statement, Val, Set<EnsuredCrySLPredicate>> existingPredicates, Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> expectedPredicates,
Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> missingPredicates) {
}
@Override
public void discoveredSeed(IAnalysisSeed curr) {
}
@Override
public void collectedValues(AnalysisSeedWithSpecification seed, Multimap<CallSiteWithParamIndex, ExtractedValue> collectedValues) {}
@Override
public void checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification, Collection<ISLConstraint> relConstraints) {}
@Override
public void seedStarted(IAnalysisSeed analysisSeedWithSpecification) {}
@Override
public void boomerangQueryStarted(Query seed, BackwardQuery q) {}
@Override
public void boomerangQueryFinished(Query seed, BackwardQuery q) {
}
@Override
public void beforePredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {}
@Override
public void beforeConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {}
@Override
public void beforeAnalysis() {}
@Override
public void afterPredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {}
@Override
public void afterConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {}
@Override
public void afterAnalysis() {}
@Override
public void onSecureObjectFound(IAnalysisSeed analysisObject) {
// TODO Auto-generated method stub
}
@Override
public void addProgress(int processedSeeds, int workListsize) {
// TODO Auto-generated method stub
}
};
}
protected void assertErrors() {
for (Cell<String, Class<?>, Integer> c : errorMarkerCountPerErrorTypeAndMethod.cellSet()) {
Integer value = c.getValue();
if (value != 0) {
if (value > 0) {
// System.out.println(
throw new RuntimeException(
"Found " + value + " too few errors of type " + c.getColumnKey() + " in method " + c.getRowKey());
} else {
// System.out.println(
throw new RuntimeException(
"Found " + Math.abs(value) + " too many errors of type " + c.getColumnKey() + " in method " + c.getRowKey());
}
}
}
}
protected void setErrorsCount(String methodSignature, Class<?> errorType, int errorMarkerCount) {
if (errorMarkerCountPerErrorTypeAndMethod.contains(methodSignature, errorType)) {
throw new RuntimeException("Error Type already specified for this method");
}
errorMarkerCountPerErrorTypeAndMethod.put(methodSignature, errorType, errorMarkerCount);
}
protected void setErrorsCount(Class<?> errorType, TruePositives tp, FalsePositives fp, FalseNegatives fn, String methodSignature) {
if (errorMarkerCountPerErrorTypeAndMethod.contains(methodSignature, errorType)) {
int errorCount = errorMarkerCountPerErrorTypeAndMethod.get(methodSignature, errorType);
errorMarkerCountPerErrorTypeAndMethod.remove(methodSignature, errorType);
errorMarkerCountPerErrorTypeAndMethod.put(methodSignature, errorType, tp.getNumberOfFindings() + fp.getNumberOfFindings() + errorCount);
} else {
errorMarkerCountPerErrorTypeAndMethod.put(methodSignature, errorType, tp.getNumberOfFindings() + fp.getNumberOfFindings());
}
}
protected void setErrorsCount(Class<?> errorType, TruePositives tp, String methodSignature) {
setErrorsCount(errorType, tp, new NoFalsePositives(), new NoFalseNegatives(), methodSignature);
}
protected void setErrorsCount(Class<?> errorType, TruePositives tp, FalseNegatives fn, String methodSignature) {
setErrorsCount(errorType, tp, new NoFalsePositives(), fn, methodSignature);
}
protected void setErrorsCount(Class<?> errorType, FalsePositives fp, String methodSignature) {
setErrorsCount(errorType, new TruePositives(0), fp, new NoFalseNegatives(), methodSignature);
}
protected void setErrorsCount(Class<?> errorType, FalseNegatives fn, String methodSignature) {
setErrorsCount(errorType, new TruePositives(0), new NoFalsePositives(), fn, methodSignature);
}
protected void setErrorsCount(ErrorSpecification errorSpecification) {
if (errorSpecification.getTotalNumberOfFindings() > 0) {
for (TruePositives tp : errorSpecification.getTruePositives()) {
setErrorsCount(tp.getErrorType(), tp, new NoFalsePositives(), new NoFalseNegatives(), errorSpecification.getMethodSignature());
}
for (FalsePositives fp : errorSpecification.getFalsePositives()) {
setErrorsCount(fp.getErrorType(), new TruePositives(0), fp, new NoFalseNegatives(), errorSpecification.getMethodSignature());
}
}
}
}
| 10,119 | 34.886525 | 175 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/BouncyCastleHeadlessTest.java | package tests.headless;
import java.io.File;
import org.junit.Ignore;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.ImpreciseValueExtractionError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
import tests.headless.FindingsType.FalseNegatives;
import tests.headless.FindingsType.TruePositives;
public class BouncyCastleHeadlessTest extends AbstractHeadlessTest {
@Ignore
@Test
public void testBCMacExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BCMacExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.BouncyCastle);
setErrorsCount("<pattern.AESTest: void testAESEngine2()>", IncompleteOperationError.class, 1);
setErrorsCount("<pattern.AESTest: void testAESLightEngine2()>", TypestateError.class, 1);
// Ignored
setErrorsCount("<pattern.AESTest: void testAESEngine1()>", ImpreciseValueExtractionError.class, 2);
setErrorsCount("<pattern.AESTest: void testAESEngine2()>", ImpreciseValueExtractionError.class, 1);
setErrorsCount("<pattern.AESTest: void testMonteCarloAndVector()>", ImpreciseValueExtractionError.class, 2);
scanner.exec();
assertErrors();
}
@Test
public void testBCSymmetricCipherExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BCSymmetricCipherExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.BouncyCastle);
setErrorsCount(RequiredPredicateError.class, new TruePositives(2), new FalseNegatives(1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216"), "<gcm_aes_example.GCMAESBouncyCastle: byte[] processing(byte[],boolean)>");
setErrorsCount("<cbc_aes_example.CBCAESBouncyCastle: void setKey(byte[])>", RequiredPredicateError.class, 1);
setErrorsCount("<cbc_aes_example.CBCAESBouncyCastle: byte[] processing(byte[],boolean)>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
@Test
@SuppressWarnings("serial")
public void testBCAsymmetricCipherExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BCAsymmetricCipherExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.BouncyCastle);
setErrorsCount(RequiredPredicateError.class, new TruePositives(1), "<crypto.RSAEngineTest: void testDecryptTwo(byte[])>");
setErrorsCount(TypestateError.class, new TruePositives(1), "<rsa_misuse.RSATest: java.lang.String Encrypt(byte[],org.bouncycastle.crypto.params.AsymmetricKeyParameter)>");
setErrorsCount(TypestateError.class, new TruePositives(1),"<crypto.RSAEngineTest: void testEncryptTwo()>");
setErrorsCount(TypestateError.class, new TruePositives(1),"<crypto.RSAEngineTest: void testDecryptTwo(byte[])>");
setErrorsCount(RequiredPredicateError.class, new TruePositives(1), new FalseNegatives(1, "Fifth parameter not randomized! //Related to https://github.com/CROSSINGTUD/CryptoAnalysis/issues/140"), "<crypto.RSAEngineTest: void testDecryptOne(byte[])>");
setErrorsCount(TypestateError.class, new TruePositives(1), "<generators.RSAKeyPairGeneratorTest: void testThree()>");
setErrorsCount(IncompleteOperationError.class, new TruePositives(1), "<generators.RSAKeyPairGeneratorTest: void testFour()>");
setErrorsCount(RequiredPredicateError.class, new TruePositives(1),"<generators.RSAKeyPairGeneratorTest: void testTwo()>");
setErrorsCount(RequiredPredicateError.class, new TruePositives(1),"<params.ParametersWithRandomTest: void testTwo()>");
setErrorsCount(RequiredPredicateError.class, new TruePositives(1), "<params.RSAPrivateCrtKeyParametersTest: void testOne()>");
scanner.exec();
assertErrors();
}
@Ignore
@Test
public void testBCDigestExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BCDigestExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.BouncyCastle);
setErrorsCount("<DigestTest: void digestWithoutUpdate()>", TypestateError.class, 1);
// False Positives due to issue #129
setErrorsCount("<DigestTest: void digestDefaultUsage()>", TypestateError.class, 1);
setErrorsCount("<DigestTest: void digestWithMultipleUpdates()>", IncompleteOperationError.class, 1);
setErrorsCount("<DigestTest: void multipleDigests()>", IncompleteOperationError.class, 2);
setErrorsCount("<DigestTest: void digestWithReset()>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
@Ignore
@Test
public void testBCSignerExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BCSignerExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.BouncyCastle);
scanner.exec();
assertErrors();
}
@Test
public void testBCEllipticCurveExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BCEllipticCurveExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.BouncyCastle);
setErrorsCount(new ErrorSpecification.Builder("<crypto.ECElGamalEncryptorTest: void testOne()>")
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<crypto.ECElGamalEncryptorTest: void testTwo()>")
.withTPs(TypestateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<crypto.ECElGamalDecryptorTest: void testOne(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<crypto.ECElGamalDecryptorTest: void testTwo(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<crypto.ECElGamalDecryptorTest: void testThree()>")
.withTPs(RequiredPredicateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<crypto.ECElGamalDecryptorTest: void testFour()>")
.withTPs(TypestateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ECPublicKeyParametersTest: void testOne(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ECPrivateKeyParametersTest: void testOne(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ECPrivateKeyParametersTest: void testOne(java.lang.String)>")
.withTPs(HardCodedError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ECPrivateKeyParametersTest: void testTwo(java.lang.String)>")
.withTPs(HardCodedError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ParametersWithRandomTest: void testOne(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ParametersWithRandomTest: void testThree(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 3)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ECDomainParametersTest: void testThree(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ECKeyGenerationParametersTest: void testTwo(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<params.ECKeyGenerationParametersTest: void testThree(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECFixedTransformTest: void testFive(java.lang.String)>")
.withTPs(TypestateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECFixedTransformTest: void testTwo(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 3)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECFixedTransformTest: void testFour(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 3)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECFixedTransformTest: void testThree(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECFixedTransformTest: void testOne(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 3)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECFixedTransformTest: void testSix(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withTPs(IncompleteOperationError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewPublicKeyTransformTest: void testThree(java.lang.String)>")
.withTPs(TypestateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewPublicKeyTransformTest: void testFour(java.lang.String)>")
.withTPs(IncompleteOperationError.class, 1)
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewPublicKeyTransformTest: void testFive(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 2, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewPublicKeyTransformTest: void testTwo(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 2, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewPublicKeyTransformTest: void testOne(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewPublicKeyTransformTest: void testSix(java.lang.String)>")
.withFNs(RequiredPredicateError.class, 2, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewRandomessTransformTest: void testThree(java.lang.String)>")
.withTPs(TypestateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewRandomessTransformTest: void testFour(java.lang.String)>")
.withTPs(IncompleteOperationError.class, 1)
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewRandomessTransformTest: void testFive(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewRandomessTransformTest: void testSix(java.lang.String)>")
.withFNs(RequiredPredicateError.class, 2, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewRandomessTransformTest: void testTwo(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 2, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<transforms.ECNewRandomessTransformTest: void testOne(java.lang.String)>")
.withTPs(RequiredPredicateError.class, 2)
.withFNs(RequiredPredicateError.class, 1, "https://github.com/CROSSINGTUD/CryptoAnalysis/issues/216")
.build());
setErrorsCount(new ErrorSpecification.Builder("<generators.ECKeyPairGeneratorTest: void testTwo(java.lang.String)>")
.withTPs(TypestateError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<generators.ECKeyPairGeneratorTest: void testThree(java.lang.String)>")
.withTPs(IncompleteOperationError.class, 1)
.build());
setErrorsCount(new ErrorSpecification.Builder("<constants.Constants: void <clinit>()>")
.withTPs(RequiredPredicateError.class, 2)
.build());
setErrorsCount(new ErrorSpecification.Builder("<constants.Constants: void <clinit>()>")
.withTPs(HardCodedError.class, 1)
.build());
scanner.exec();
assertErrors();
}
}
| 13,701 | 54.25 | 253 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/BragaCryptoGoodusesTest.java | package tests.headless;
import java.io.File;
import org.junit.Ignore;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.ForbiddenMethodError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
import tests.headless.FindingsType.FalsePositives;
/**
* @author Enri Ozuni
*/
public class BragaCryptoGoodusesTest extends AbstractHeadlessTest {
/**
* The following headless tests are deducted from the Braga et al. paper which
* benchmarks several static analyzer tools against several hundred test
* projects containing various Cryptographic providers of the JCA framework. For
* the creation of these headless tests, various projects from Braga paper were
* considered and used for testing the provider detection functionality. The
* test projects of the paper can be found in the link below:
*
* https://bitbucket.org/alexmbraga/cryptogooduses/src/master/
*/
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/cai/alwaysDefineCSP/
@Ignore
@Test
public void alwaysDefineCSPExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/alwaysDefineCSP")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.DefinedProvider1: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<example.DefinedProvider2: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<example.DefinedProvider2: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<example.DefinedProvider3: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.DefinedProvider4: void main(java.lang.String[])>", IncompleteOperationError.class, 6);
setErrorsCount("<example.DefinedProvider5: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<example.DefinedProvider6: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.DefinedProvider6: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.DefinedProvider7: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.DefinedProvider7: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.DefinedProvider7: void main(java.lang.String[])>", TypestateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/cib/avoidCodingErros/
@Test
public void avoidCodingErrorsExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidCodingErrors")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.PBEwLargeCountAndRandomSalt: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PBEwLargeCountAndRandomSalt: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PBEwLargeCountAndRandomSalt: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.PBEwLargeCountAndRandomSalt: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<example.DoNotSaveToString: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.GenerateRandomIV: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.GenerateRandomIV: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<example.GenerateRandomIV: void main(java.lang.String[])>", TypestateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkm/avoidConstantPwdPBE/
@Test
public void avoidConstantPwdPBEExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidConstantPwdPBE").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.PBEwParameterPassword: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PBEwParameterPassword: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.PBEwParameterPassword: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<example.PBEwParameterPassword: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/enc/avoidDeterministicRSA/
@Test
public void avoidDeterministicRSAExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidDeterministicRSA").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.UseOAEPForRSA: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.UseOAEPForRSA: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.UseOAEPForRSA: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<example.UsePKCS1ForRSA: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.UsePKCS1ForRSA: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<example.UsePKCS1ForRSA: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/br/avoidFixedPredictableSeed/
@Test
public void avoidFixedPredictableSeedExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidFixedPredictableSeed").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount(RequiredPredicateError.class, new FalsePositives(1, ""), "<example.DoNotUseWeakSeed1: void main(java.lang.String[])>");
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkm/avoidHardcodedKeys/
@Test
public void avoidHardcodedKeysExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidHardcodedKeys").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.UseDynamicKeyFor3DES: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<example.UseDynamicKeyFor3DES: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.UseDynamicKeyFor3DES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.UseDynamicKeyForAES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.UseDynamicKeyforMAC1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkm/avoidImproperKeyLen/
@Test
public void avoidImproperKeyLenExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidImproperKeyLen").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_1: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pdf/avoidInsecureDefaults/
@Test
public void avoidInsecureDefaultsExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidInsecureDefaults").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.UseQualifiedNameForPBE1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.UseQualifiedNameForPBE1: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<example.UseQualifiedNameForPBE1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.UseQualifiedNameForPBE1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.UseExplicitMode1: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.UseExplicitMode1: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<example.UseExplicitMode1: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<example.UseExplicitPadding1: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.UseExplicitPadding1: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<example.UseExplicitPadding1: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<example.UseQualifiedNameForRSAOAEP: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.UseQualifiedNameForRSAOAEP: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.UseQualifiedParamsForRSAOAEP: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.UseQualifiedParamsForRSAOAEP: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/wc/avoidInsecureHash/
@Test
public void avoidInsecureHashExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidInsecureHash")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.UseSHA2_1: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<example.UseSHA2_2: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.UseSHA2_2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.UseSHA3_1: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<example.UseSHA3_1: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.UseSHA3_2: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/wc/avoidInsecureMAC/
@Test
public void avoidInsecureMACExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidInsecureMAC")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/enc/avoidInsecurePadding/
@Test
public void avoidInsecurePaddingExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidInsecurePadding").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.OAEP_2048x256_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.OAEP_2048x256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.OAEP_2048x256_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.OAEP_2048x256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.OAEP_2048x384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.OAEP_2048x384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.OAEP_2048x384_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.OAEP_2048x384_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.OAEP_2048x512_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.OAEP_2048x512_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.OAEP_2048x512_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.OAEP_2048x512_2: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/sign/avoidInsecurePadding/
@Test
public void avoidInsecurePaddingSignExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidInsecurePaddingSign").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.PSSwSHA256Signature: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSSwSHA256Signature: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PSSwSHA384Signature: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSSwSHA384Signature: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PSSwSHA512Signature: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSSwSHA512Signature: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/wc/avoidInsecureSymEnc/
@Test
public void avoidInsecureSymEncExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidInsecureSymEnc").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.UseAEADwAES_GCM: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.UseAES_CTR: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<example.UseAES_CTR: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkm/avoidKeyReuseInStreams/
@Test
public void avoidKeyReuseInStreamsExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidKeyReuseInStreams").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.DoNotReuseKeyStreamCipher1: void main(java.lang.String[])>", RequiredPredicateError.class, 3);
setErrorsCount("<example.DoNotReuseKeyStreamCipher1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.DoNotReuseKeyStreamCipher2: void main(java.lang.String[])>", RequiredPredicateError.class, 3);
setErrorsCount("<example.DoNotReuseKeyStreamCipher2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.DoNotReuseKeyStreamCipher3: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.DoNotReuseKeyStreamCipher4: void main(java.lang.String[])>", RequiredPredicateError.class, 3);
setErrorsCount("<example.DoNotReuseKeyStreamCipher4: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.DoNotReuseKeyStreamCipher5: void main(java.lang.String[])>", RequiredPredicateError.class, 3);
setErrorsCount("<example.DoNotReuseKeyStreamCipher5: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pdf/avoidSideChannels/
@Test
public void avoidSideChannelsExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidSideChannels")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/br/avoidStatisticPRNG/
@Test
public void avoidStatisticPRNGExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/avoidStatisticPRNG").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/icv/completeValidation/
@Test
public void completeValidationExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/completeValidation").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.SSLClientCertPathCRLValidation: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<example.SSLClientCompleteValidation: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/ka/DHandECDH/
@Test
public void DHandECDHExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/DHandECDH")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.NonAuthenticatedEphemeralECDH_128: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<example.NonAuthenticatedEphemeralECDH_128: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<example.NonAuthenticatedEphemeralECDH_192: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<example.NonAuthenticatedEphemeralECDH_192: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<example.NonAuthenticatedEphemeralECDH_256: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<example.NonAuthenticatedEphemeralECDH_256: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<example.NonAuthenticatedDH_2048: void main(java.lang.String[])>", RequiredPredicateError.class, 6);
setErrorsCount("<example.NonAuthenticatedDH_2048: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.NonAuthenticatedEphemeralDH_2048: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/sign/digSignDSAandECDSA/
@Test
public void digSignDSAandECDSAExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/digSignDSAandECDSA").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.BC_128bits_DSA3072xSHA256: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.BC_128bits_DSA3072xSHA256: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.RandomMessageNonceECDSA: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<example.SUN_112bits_ECDSA224wSHA224: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.SUN_112bits_ECDSA224wSHA224: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<example.SUN_192bits_ECDSA384wSHA384: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.SUN_192bits_ECDSA384wSHA384: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<example.SUN_256bits_ECDSA571wSHA512: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.SUN_256bits_ECDSA571wSHA512: void main(java.lang.String[])>", ConstraintError.class, 3);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/sign/digSignRSA/
@Test
public void digSignRSAExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/digSignRSA")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.PKCS1_112bitsSign2048xSHA256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PKCS1_112bitsSign2048xSHA256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PKCS1_128bitsSign3072xSHA256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PKCS1_128bitsSign3072xSHA256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PKCS1_192bitsSign7680xSHA384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PKCS1_192bitsSign7680xSHA384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.PKCS1_192bitsSign7680xSHA384_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PKCS1_192bitsSign7680xSHA384_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PKCS1_192bitsSign7680xSHA384_2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.PKCS1_192bitsSign7680xSHA384_2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PSS_112bitsSign2048xSHA256_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PSS_112bitsSign2048xSHA256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSS_112bitsSign2048xSHA256_2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PSS_112bitsSign2048xSHA256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSS_128bitsSign3072xSHA256_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PSS_128bitsSign3072xSHA256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSS_128bitsSign3072xSHA256_2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.PSS_128bitsSign3072xSHA256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSS_192bitsSign7680xSHA384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSS_192bitsSign7680xSHA384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.PSS_192bitsSign7680xSHA384_1: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<example.PSS_192bitsSign7680xSHA384_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.PSS_192bitsSign7680xSHA384_2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.PSS_192bitsSign7680xSHA384_2: void main(java.lang.String[])>", ConstraintError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/cib/doNotPrintSecrets/
@Test
public void doNotPrintSecretsExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/doNotPrintSecrets")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.DoNotPrintECDHPrivKey1: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<example.DoNotPrintECDHPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.DoNotPrintECDHSecret1: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<example.DoNotPrintECDHSecret1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.DoNotPrintECDSAPrivKey1: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<example.DoNotPrintECDSAPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.DoNotPrintPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.DoNotPrintPrivKey1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.DoNotPrintSecKey1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.DoNotPrintDHSecret1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.DoNotPrintDHPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pdf/encryptThenHashOrMAC/
@Test
public void encryptThenHashOrMACExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/encryptThenHashOrMAC").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.EncryptThenHashCiphertextAndIV: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.EncryptThenHashCiphertextAndIV: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.EncryptThenMacCiphertextAndIV: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.EncryptThenMacCiphertextAndIV: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/ivm/randomIV/
@Test
public void randomIVExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/randomIV")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.UseRandomIVsForCBC: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<example.UseRandomIVsForCBC: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<example.UseRandomIVsForCBC: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<example.UseRandomIVsForCFB: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.UseRandomIVsForCFB: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.UseRandomIVsForCFB: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<example.UseRandomIVsForCFB128: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.UseRandomIVsForCFB128: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<example.UseRandomIVsForCFB128: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<example.UseRandomIVsForCFB128: void main(java.lang.String[])>", ConstraintError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/enc/secureConfigsRSA/
@Test
public void secureConfigsRSAExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/secureConfigsRSA")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig112bitsRSA_2048x256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_3072x384_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig128bitsRSA_4096x512_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x384_2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.SecureConfig192bitsRSA_7680x512_2: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pkc/ecc/securecurves/
@Test
public void securecurvesExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/securecurves")
.getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptogooduses/src/master/pdf/secureStreamCipher/
@Test
public void secureStreamCipherExamples() {
String mavenProjectPath = new File(
"../CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/secureStreamCipher").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.UseMacWithMaleableStream: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.UseMacWithMaleableStream: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
}
| 37,755 | 62.884941 | 136 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/BragaCryptoMisusesTest.java | package tests.headless;
import java.io.File;
import org.junit.Ignore;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.ForbiddenMethodError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
import tests.headless.FindingsType.FalsePositives;
/**
* @author Enri Ozuni
*/
public class BragaCryptoMisusesTest extends AbstractHeadlessTest {
/**
* The following headless tests are deducted from the Braga et al. paper which benchmarks
* several static analyzer tools against several hundred test projects containing various
* Cryptographic providers of the JCA framework. For the creation of these headless tests,
* various projects from Braga paper were considered and used for testing the provider
* detection functionality. The test projects of the paper can be found in the link below:
*
* https://bitbucket.org/alexmbraga/cryptomisuses/src/master/
*/
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/wc/brokenInsecureHash/
@Test
public void brokenInsecureHashExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/brokenInsecureHash").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes1: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes1: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes2: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes3: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes3: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes4: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes4: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes5: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<wc.brokenInsecureHash.InsecureHashes5: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/wc/brokenInsecureMAC/
@Test
public void brokenInsecureMACExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/brokenInsecureMAC").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<wc.brokenInsecureMAC.InsecureMAC1: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<wc.brokenInsecureMAC.InsecureMAC1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<wc.brokenInsecureMAC.InsecureMAC3: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.brokenInsecureMAC.InsecureMAC3: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<wc.brokenInsecureMAC.InsecureMAC4: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.brokenInsecureMAC.InsecureMAC4: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/icv/brokenSSLorTLS/
@Test
public void brokenSSLorTLSExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/brokenSSLorTLS").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt3: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt3: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt4: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt4: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt5: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt5: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt6: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<icv.brokenSSLorTLS.SSLctxNoKeyMgmtNoTrustMgmt6: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/cib/buggyIVgen/
@Test
public void buggyIVgenExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/buggyIVgen").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<cib.buggyIVgen.BuggyIVGen1: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<cib.buggyIVgen.BuggyIVGen1: void main(java.lang.String[])>", RequiredPredicateError.class, 7);
setErrorsCount("<cib.buggyIVgen.BuggyIVGen1: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<cib.buggyIVgen.BuggyIVGen2: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<cib.buggyIVgen.BuggyIVGen2: void main(java.lang.String[])>", RequiredPredicateError.class, 7);
setErrorsCount("<cib.buggyIVgen.BuggyIVGen2: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/ivm/constantIV/
@Test
public void constantIVExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/constantIV").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<ivm.constantIV.FixedIV1: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<ivm.constantIV.FixedIV1: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<ivm.constantIV.FixedIV1: void main(java.lang.String[])>", RequiredPredicateError.class, 7);
setErrorsCount("<ivm.constantIV.FixedIV2: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<ivm.constantIV.FixedIV2: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<ivm.constantIV.FixedIV2: void main(java.lang.String[])>", RequiredPredicateError.class, 7);
setErrorsCount("<ivm.constantIV.SimpleIVConstant: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkm/constantKey/
@Test
public void constantKeyExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/constantKey").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkm.constantKey.ConstantKey3DES: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkm.constantKey.ConstantKey3DES: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkm.constantKey.ConstantKey3DES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.constantKey.ConstantKeyAES1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkm.constantKey.ConstantKeyAES1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.constantKey.ConstantKeyAES2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkm.constantKey.ConstantKeyAES2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.constantKey.ConstantKeyAES3: void main(java.lang.String[])>", RequiredPredicateError.class, 3);
setErrorsCount("<pkm.constantKey.ConstantKeyAES3: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.constantKey.HardCodedKey: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkm.constantKey.ConstantKeyforMAC: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkm/constPwd4PBE/
@Test
public void constPwd4PBEExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/constPwd4PBE").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE1: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE1: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE2: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.constPwd4PBE.ConstPassword4PBE2: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/wc/customCrypto/
@Test
public void customCryptoExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/customCrypto").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<wc.customCrypto.Manual3DES: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<wc.customCrypto.Manual3DES: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.customCrypto.Manual3DES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<wc.customCrypto.RawSignatureRSA: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<wc.customCrypto.RawSignatureRSA: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<wc.customCrypto.RawSignatureRSAwHash: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<wc.customCrypto.RawSignatureRSAwHash: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/enc/deterministicCrypto/
@Test
public void deterministicCryptoExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/deterministicCrypto").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA1: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA1: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA1: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA2: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA2: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA3: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA3: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA3: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.enc.deterministicCrypto.DeterministicEncryptionRSA3: void main(java.lang.String[])>", TypestateError.class, 0);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/wc/deterministicSymEnc/
@Test
public void deterministicSymEncExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/deterministicSymEnc").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<wc.deterministicSymEnc.DeterministicEncryptionAESwECB1: void main(java.lang.String[])>", ConstraintError.class, 6);
setErrorsCount("<wc.deterministicSymEnc.DeterministicEncryptionAESwECB1: void main(java.lang.String[])>", IncompleteOperationError.class, 12);
setErrorsCount("<wc.deterministicSymEnc.DeterministicEncryptionAESwECB1: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<wc.deterministicSymEnc.DeterministicEncryptionAESwECB2: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<wc.deterministicSymEnc.DeterministicEncryptionAESwECB2: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<wc.deterministicSymEnc.DeterministicEncryptionAESwECB2: void main(java.lang.String[])>", TypestateError.class, 0);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/br/fixedSeed/
@Test
public void fixedSeedExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/fixedSeed").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<br.fixedSeed.FixedSeed1: void main(java.lang.String[])>", TypestateError.class, 4);
setErrorsCount("<br.fixedSeed.FixedSeed1: void main(java.lang.String[])>", RequiredPredicateError.class, 7);
setErrorsCount("<br.fixedSeed.FixedSeed1: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<br.fixedSeed.FixedSeed1: void main(java.lang.String[])>", IncompleteOperationError.class, 6);
setErrorsCount("<br.fixedSeed.FixedSeed2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<br.fixedSeed.FixedSeed3: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<br.fixedSeed.FixedSeed4: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkm/ImproperKeyLen/
@Test
public void improperKeyLenExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/ImproperKeyLen").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkm.ImproperKeyLen.ImproperKeySizeRSA1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkm.ImproperKeyLen.ImproperKeySizeRSA2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkm.ImproperKeyLen.ImproperKeySizeRSA3: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkm.ImproperKeyLen.ImproperKeySizeRSA4: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkm.ImproperKeyLen.ImproperKeySizeRSA5: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkm.ImproperKeyLen.ImproperKeySizeRSA6: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/icv/incompleteValidation/
@Test
public void incompleteValidationExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/incompleteValidation").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<icv.incompleteValidation.ValidateCertChainButNoCRL: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pdf/insecureComboHashEnc/
@Test
public void insecureComboHashEncExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/insecureComboHashEnc").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboEncryptAndHash: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboEncryptAndHash: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboEncryptThenHash1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboEncryptThenHash1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboEncryptThenHash2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboEncryptThenHash2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboHashThenEncrypt: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.insecureComboHashEnc.ManualComboHashThenEncrypt: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pdf/insecureComboMacEnc/
@Test
public void insecureComboMacEncExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/insecureComboMacEnc").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboEncryptAndMAC: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboEncryptAndMAC: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboEncryptThenMAC1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboEncryptThenMAC1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboEncryptThenMAC2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboEncryptThenMAC2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboMACThenEncrypt: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pdf.insecureComboMacEnc.ManualComboMACThenEncrypt: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/ecc/insecurecurves/
@Test
public void insecurecurvesExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/insecurecurves").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pdf/insecureDefault/
@Test
public void insecureDefaultExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/insecureDefault").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultPBE: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultPBE: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultPBE: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefault3DES: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pdf.insecureDefault.InsecureDefault3DES: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefault3DES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultAES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultAES: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultOAEP: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultOAEP: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultOAEP: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultRSA: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultRSA: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pdf.insecureDefault.InsecureDefaultRSA: void main(java.lang.String[])>", TypestateError.class, 0);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/enc/insecurePadding/
@Test
public void insecurePaddingExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/insecurePadding").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA1: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA1: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA1: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA2: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA2: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA3: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA3: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
setErrorsCount("<pkc.enc.insecurePadding.InsecurePaddingRSA3: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/sign/insecurePadding/
@Test
public void insecurePaddingSignExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/insecurePaddingSign").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkc.sign.insecurePaddingSign.PKCS1Signature: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PKCS1Signature: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PKCS1Signature1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PKCS1Signature2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PSSwSHA1Signature: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PSSwSHA1Signature: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PSSwSHA1Signature1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PSSwSHA1Signature1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PSSwSHA1Signature2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.insecurePaddingSign.PSSwSHA1Signature2: void main(java.lang.String[])>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pdf/insecureStreamCipher/
@Test
public void insecureStreamCipherExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/insecureStreamCipher").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pdf.insecureStreamCipher.ConfusingBlockAndStream: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pdf.insecureStreamCipher.ConfusingBlockAndStream: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<pdf.insecureStreamCipher.MalealableStreamCipher: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<pdf.insecureStreamCipher.MalealableStreamCipher: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<pdf.insecureStreamCipher.MalealableStreamCipher: void main(java.lang.String[])>", TypestateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/ka/issuesDHandECDH/
@Test
public void issuesDHandECDHExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/issuesDHandECDH").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralDH_1024: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralDH_1024: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralDH_512: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralDH_512: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralECDH_112: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralECDH_112: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralECDH_80: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedEphemeralECDH_80: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedDH_512: void main(java.lang.String[])>", RequiredPredicateError.class, 6);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedDH_512: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.ka.issuesDHandECDH.NonAuthenticatedDH_1024: void main(java.lang.String[])>", RequiredPredicateError.class, 6);
setErrorsCount(IncompleteOperationError.class, new FalsePositives(1, ""), "<pkc.ka.issuesDHandECDH.NonAuthenticatedDH_1024: void main(java.lang.String[])>");
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkm/keyReuseInStreamCipher/
@Test
public void keyReuseInStreamCipherExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/keyReuseInStreamCipher").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher1: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher2: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher3: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher3: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher4: void main(java.lang.String[])>", RequiredPredicateError.class, 6);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher4: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher5: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkm.keyReuseInStreamCipher.KeyReuseStreamCipher5: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/ivm/nonceReuse/
@Test
public void nonceReuseExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/nonceReuse").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<ivm.nonceReuse.NonceReuse1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<ivm.nonceReuse.NonceReuse1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/cib/nullcipher/
@Test
public void nullcipherExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/nullcipher").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/cib/paramsPBE/
@Test
public void paramsPBEExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/paramsPBE").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<cib.paramsPBE.PBEwConstSalt1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cib.paramsPBE.PBEwConstSalt1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwConstSalt1: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwConstSalt1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwSmallCount1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cib.paramsPBE.PBEwSmallCount1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwSmallCount1: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwSmallCount1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwSmallSalt: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cib.paramsPBE.PBEwSmallSalt: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwSmallSalt: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<cib.paramsPBE.PBEwSmallSalt: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/br/predictableSeed/
@Test
public void predictableSeedExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/predictableSeed").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<br.predictableSeed.ReusedSeed: void main(java.lang.String[])>", TypestateError.class, 0);
setErrorsCount("<br.predictableSeed.ReusedSeed: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<br.predictableSeed.LowEntropySeed1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<br.predictableSeed.LowEntropySeed2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<br.predictableSeed.LowEntropySeed3: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<br.predictableSeed.LowEntropySeed4: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/cib/printPrivSecKey/
@Test
public void printPrivSecKeyExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/printPrivSecKey").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<cib.printPrivSecKey.PrintECDHPrivKey1: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<cib.printPrivSecKey.PrintECDHPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cib.printPrivSecKey.PrintECDHSecret1: void main(java.lang.String[])>", ConstraintError.class, 4);
setErrorsCount("<cib.printPrivSecKey.PrintECDHSecret1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cib.printPrivSecKey.PrintECDSAPrivKey1: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<cib.printPrivSecKey.PrintECDSAPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cib.printPrivSecKey.PrintPrivKey1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<cib.printPrivSecKey.PrintPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<cib.printPrivSecKey.PrintSecKey1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<cib.printPrivSecKey.PrintDHSecret1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cib.printPrivSecKey.PrintDHPrivKey1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/wc/riskyInsecureCrypto/
@Test
public void riskyInsecureCryptoExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/riskyInsecureCrypto").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoPBE: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoPBE: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoPBE: void main(java.lang.String[])>", ForbiddenMethodError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCrypto3DES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCrypto3DES: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCrypto3DES: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoBlowfish: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoBlowfish: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoBlowfish: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoDES: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoDES: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoDES: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoDES_StreamCipher: void main(java.lang.String[])>", TypestateError.class, 5);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoDES_StreamCipher: void main(java.lang.String[])>", ConstraintError.class, 5);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoDES_StreamCipher: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoRC4_StreamCipher: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoRC4_StreamCipher: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<wc.riskyInsecureCrypto.InsecureCryptoRC4_StreamCipher: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pdf/sideChannelAttacks/
@Test
public void sideChannelAttacksExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/sideChannelAttacks").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pdf.sideChannelAttacks.HashVerificationVariableTime: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.sideChannelAttacks.PaddingOracle: boolean oracle(byte[],byte[])>", ConstraintError.class, 1);
setErrorsCount("<pdf.sideChannelAttacks.PaddingOracle: boolean oracle(byte[],byte[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pdf.sideChannelAttacks.PaddingOracle: byte[] encripta()>", RequiredPredicateError.class, 3);
setErrorsCount("<pdf.sideChannelAttacks.PaddingOracle: byte[] encripta()>", ConstraintError.class, 1);
setErrorsCount("<pdf.sideChannelAttacks.PaddingOracle: void <clinit>()>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/ivm/staticCounterCTR/
@Test
public void staticCounterCTRExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/staticCounterCTR").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<ivm.staticCounterCTR.StaticCounterCTR1: void main(java.lang.String[])>", RequiredPredicateError.class, 5);
setErrorsCount("<ivm.staticCounterCTR.StaticCounterCTR1: void main(java.lang.String[])>", TypestateError.class, 2);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/br/statisticPRNG/
@Test
public void statisticPRNGExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/statisticPRNG").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/cai/undefinedCSP/
@Test
@Ignore
public void undefinedCSPExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/undefinedCSP").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider1: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider2: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider2: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount(RequiredPredicateError.class, new FalsePositives(1, ""), "<cai.undefinedCSP.UndefinedProvider3: void main(java.lang.String[])>");
setErrorsCount("<cai.undefinedCSP.UndefinedProvider4: void main(java.lang.String[])>", IncompleteOperationError.class, 2);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider5: void main(java.lang.String[])>", IncompleteOperationError.class, 3);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider6: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider6: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider7: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider7: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider7: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider8: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider8: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<cai.undefinedCSP.UndefinedProvider8: void main(java.lang.String[])>", IncompleteOperationError.class, 4);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/enc/weakConfigsRSA/
@Test
public void weakConfigsRSAExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/weakConfigsRSA").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x160_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x160_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x160_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x256_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x256_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x384_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x384_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_1024x384_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_2048x160_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_2048x160_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_3072x160_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_3072x160_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_384x160_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_384x160_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_384x160_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_4096x160_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_4096x160_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_512x160_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_512x160_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_512x160_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_768x160_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_768x160_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_768x160_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_768x256_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_768x256_1: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.enc.weakConfigsRSA.ImproperConfigRSA_768x256_1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/sign/weakSignatureECDSA/
@Test
@Ignore
public void weakSignatureECDSAExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/weakSignatureECDSA").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkc.sign.weakSignatureECDSA.RepeatedMessageNonceECDSA_1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureECDSA.RepeatedMessageNonceECDSA_2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureECDSA.RepeatedMessageNonceECDSA_3: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureECDSA.RepeatedMessageNonceECDSA_4: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureECDSA.SUN_80bits_ECDSA112wNONE1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureECDSA.SUN_80bits_ECDSA112wNONE1: void main(java.lang.String[])>", ConstraintError.class, 5);
setErrorsCount("<pkc.sign.weakSignatureECDSA.SUN_80bits_ECDSA112wNONE2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureECDSA.SUN_80bits_ECDSA112wNONE2: void main(java.lang.String[])>", ConstraintError.class, 3);
setErrorsCount("<pkc.sign.weakSignatureECDSA.SUN_80bits_ECDSA112wSHA1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureECDSA.SUN_80bits_ECDSA112wSHA1: void main(java.lang.String[])>", ConstraintError.class, 3);
scanner.exec();
assertErrors();
}
// This test case corresponds to the following project in BragaCryptoBench:
// https://bitbucket.org/alexmbraga/cryptomisuses/src/master/pkc/sign/weakSignatureRSA/
@Test
public void weakSignatureRSAExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/BragaCryptoBench/cryptomisuses/weakSignatureRSA").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<pkc.sign.weakSignatureRSA.PKCS1Sign1024xSHA1_1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureRSA.PKCS1Sign1024xSHA1_1: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureRSA.PKCS1Sign1024xSHA1_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.weakSignatureRSA.PKCS1Sign1024xSHA256_2: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureRSA.PKCS1Sign1024xSHA256_2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.sign.weakSignatureRSA.PKCS1Sign1024xSHA256_2: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.weakSignatureRSA.PSSw1024xSHA1_1: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureRSA.PSSw1024xSHA1_1: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<pkc.sign.weakSignatureRSA.PSSw1024xSHA1_1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<pkc.sign.weakSignatureRSA.PSSw1024xSHA256_2: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<pkc.sign.weakSignatureRSA.PSSw1024xSHA256_2: void main(java.lang.String[])>", TypestateError.class, 1);
scanner.exec();
assertErrors();
}
}
| 56,620 | 71.312899 | 159 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/CogniCryptGeneratedCodeTest.java | package tests.headless;
import java.io.File;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.RequiredPredicateError;
public class CogniCryptGeneratedCodeTest extends AbstractHeadlessTest {
@Test
public void fileEncryptor() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/FileEncryptor").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
//All the following errors are false positives
setErrorsCount("<Crypto.KeyDeriv: javax.crypto.SecretKey getKey(char[])>", RequiredPredicateError.class, 2);
setErrorsCount("<Crypto.KeyDeriv: javax.crypto.SecretKey getKey(char[])>", HardCodedError.class, 1);
setErrorsCount("<Crypto.Enc: byte[] encrypt(byte[],javax.crypto.SecretKey)>", RequiredPredicateError.class, 1);
setErrorsCount("<Crypto.Enc: byte[] decrypt(byte[],javax.crypto.SecretKey)>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
@Test
public void userAuthenticator() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/UserAuthenticator").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
//All the following errors are false positives
setErrorsCount("<Crypto.PWHasher: java.lang.Boolean verifyPWHash(char[],java.lang.String)>", RequiredPredicateError.class, 2);
setErrorsCount("<Crypto.PWHasher: java.lang.Boolean verifyPWHash(char[],java.lang.String)>", HardCodedError.class, 1);
setErrorsCount("<Crypto.PWHasher: java.lang.String createPWHash(char[])>", RequiredPredicateError.class, 1);
setErrorsCount("<Crypto.PWHasher: java.lang.String createPWHash(char[])>", HardCodedError.class, 1);
scanner.exec();
assertErrors();
}
}
| 1,916 | 41.6 | 128 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/CryptoGuardTest.java | package tests.headless;
import java.io.File;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.NeverTypeOfError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
import tests.headless.FindingsType.FalseNegatives;
import tests.headless.FindingsType.TruePositives;
/**
* @author Enri Ozuni
*/
public class CryptoGuardTest extends AbstractHeadlessTest {
/**
* The following Headless tests are deducted from the CryptoGuard benchmarking tool
* that detects various Cryptographic API misuses. For the creating these Headless
* tests, various projects from CryptoGuard were considered and can be found in the
* following link: https://github.com/CryptoGuardOSS/cryptoapi-bench
*/
@Test
public void brokenCryptoExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/brokencrypto").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/brokencrypto/BrokenCryptoABICase1.java
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase1: void doCrypto(java.lang.String)>", ConstraintError.class, 1);
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase1: void doCrypto(java.lang.String)>", IncompleteOperationError.class, 1);
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase1: void doCrypto(java.lang.String)>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/brokencrypto/BrokenCryptoABICase2.java
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase2: void doCrypto(java.lang.String)>", ConstraintError.class, 2);
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase2: void doCrypto(java.lang.String)>", RequiredPredicateError.class, 1);
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase2: void doCrypto(java.lang.String)>", IncompleteOperationError.class, 1);
// ABICase3, ABICase4, ABICase9 not included as tests due to being similar to ABICase1 and ABICase2 above
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/brokencrypto/BrokenCryptoABICase5.java
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase5: void doCrypto()>", RequiredPredicateError.class, 1);
setErrorsCount("<example.brokencrypto.BrokenCryptoABICase5: void doCrypto()>", IncompleteOperationError.class, 1);
setErrorsCount(ConstraintError.class, new TruePositives(1), new FalseNegatives(1, "ConstraintError not caught! //Related to https://github.com/CROSSINGTUD/CryptoAnalysis/issues/163"), "<example.brokencrypto.BrokenCryptoABICase5: void doCrypto()>");
// ABICase6, -7, -8, -10 not included as tests due to being similar to ABICase5 above
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/brokencrypto/BrokenCryptoBBCase3.java
setErrorsCount("<example.brokencrypto.BrokenCryptoBBCase3: void go()>", ConstraintError.class, 2);
setErrorsCount("<example.brokencrypto.BrokenCryptoBBCase3: void go()>", RequiredPredicateError.class, 1);
setErrorsCount("<example.brokencrypto.BrokenCryptoBBCase3: void go()>", IncompleteOperationError.class, 1);
// BBCase1, BBCase2, BBCase4, BBCase5 not included as tests due to being similar to BBCase3 above
// Test cases regarding ecbcrypto project were not added, due to being similar to
// all the test cases above:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/tree/master/src/main/java/org/cryptoapi/bench/ecbcrypto
scanner.exec();
assertErrors();
}
@Test
public void brokenHashExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/brokenhash").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/brokenhash/BrokenHashABICase1.java
setErrorsCount("<example.brokenhash.BrokenHashABICase1: void go(java.lang.String,java.lang.String)>", ConstraintError.class, 1);
// ABICase2, -3, -4 not included as tests due to being similar to ABICase1 above
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/brokenhash/BrokenHashABICase5.java
setErrorsCount(ConstraintError.class, new FalseNegatives(1, "ConstraintError not caught! //Related to https://github.com/CROSSINGTUD/CryptoAnalysis/issues/163"), "<example.brokenhash.BrokenHashABICase5: void go(java.lang.String)>");
// ABICase6, -7, -8 not included as tests due to being similar to ABICase5 above
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/brokenhash/BrokenHashBBCase2.java
setErrorsCount("<example.brokenhash.BrokenHashBBCase2: void main(java.lang.String[])>", ConstraintError.class, 1);
// BBCase1, -3, -4 not included due to being similar to BBCase2 above
scanner.exec();
assertErrors();
}
@Test
public void ecbCryptoExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/ecbcrypto").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/ecbcrypto/EcbInSymmCryptoABICase1.java
setErrorsCount("<example.ecbcrypto.EcbInSymmCryptoABICase1: void go(java.lang.String)>", ConstraintError.class, 1);
setErrorsCount("<example.ecbcrypto.EcbInSymmCryptoABICase1: void go(java.lang.String)>", IncompleteOperationError.class, 1);
// ABICase3 not included as tests due to being similar to ABICase1 above
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/ecbcrypto/EcbInSymmCryptoABICase2.java
setErrorsCount("<example.ecbcrypto.EcbInSymmCryptoABICase2: void go()>", IncompleteOperationError.class, 1);
// ABICase3 not included as tests due to being similar to ABICase2 above
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/ecbcrypto/EcbInSymmCryptoBBCase1.java
setErrorsCount("<example.ecbcrypto.EcbInSymmCryptoBBCase1: void go()>", ConstraintError.class, 1);
setErrorsCount("<example.ecbcrypto.EcbInSymmCryptoBBCase1: void go()>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/ecbcrypto/EcbInSymmCryptoCorrected.java
setErrorsCount("<example.ecbcrypto.EcbInSymmCryptoCorrected: void go()>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void insecureAsymmetricCryptoExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/insecureasymmetriccrypto").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/insecureasymmetriccrypto/InsecureAsymmetricCipherABICase1.java
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherABICase1: void go(java.security.KeyPairGenerator,java.security.KeyPair)>", IncompleteOperationError.class, 2);
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherABICase1: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherABICase1: void go(java.security.KeyPairGenerator,java.security.KeyPair)>", RequiredPredicateError.class, 2);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/insecureasymmetriccrypto/InsecureAsymmetricCipherABICase2.java
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherABICase2: void go(java.security.KeyPairGenerator,java.security.KeyPair)>", IncompleteOperationError.class, 2);
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherABICase2: void go(java.security.KeyPairGenerator,java.security.KeyPair)>", RequiredPredicateError.class, 2);
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherABICase2: void main(java.lang.String[])>", ConstraintError.class, 1);
// In the case above, misuse is caught correctly, but the keysize is reported to be 0
// and not 1024, as it really is. This is caused because of the structure of the project
// as explained in the issue: https://github.com/CROSSINGTUD/CryptoAnalysis/issues/163
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/insecureasymmetriccrypto/InsecureAsymmetricCipherBB Case1.java
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherBBCase1: void go()>", IncompleteOperationError.class, 2);
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherBBCase1: void go()>", ConstraintError.class, 1);
setErrorsCount("<example.insecureasymmetriccrypto.InsecureAsymmetricCipherBBCase1: void go()>", RequiredPredicateError.class, 2);
scanner.exec();
assertErrors();
}
@Test
public void pbeIterationExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/pbeiteration").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/pbeiteration/LessThan1000IterationPBEABICase1.java
setErrorsCount("<example.pbeiteration.LessThan1000IterationPBEABICase1: void key2(int)>", ConstraintError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/pbeiteration/LessThan1000IterationPBEBBCase1.java
setErrorsCount("<example.pbeiteration.LessThan1000IterationPBEBBCase1: void key2()>", ConstraintError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/pbeiteration/LessThan1000IterationPBEABHCase1.java
setErrorsCount(ConstraintError.class, new FalseNegatives(1, "ConstraintError not caught! //Related to https://github.com/CROSSINGTUD/CryptoAnalysis/issues/165"), "<example.pbeiteration.LessThan1000IterationPBEABHCase1: void key2()>");
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/pbeiteration/LessThan1000IterationPBEABICase2.java
setErrorsCount("<example.pbeiteration.LessThan1000IterationPBEABICase2: void key2()>", ConstraintError.class, 1);
// In the case above, misuse is caught correctly, but the count is reported to be 0
// and not 20, as it really is. This is caused because of the structure of the project
// as explained in the issue: https://github.com/CROSSINGTUD/CryptoAnalysis/issues/163
scanner.exec();
assertErrors();
}
@Test
public void predictableCryptographicKeyExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/predictablecryptographickey").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablecryptographickey/PredictableCryptographicKeyABHCase1.java
setErrorsCount("<example.predictablecryptographickey.PredictableCryptographicKeyABHCase1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablecryptographickey/PredictableCryptographicKeyABICase1.java
setErrorsCount("<example.predictablecryptographickey.PredictableCryptographicKeyABICase1: void go(java.lang.String)>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablecryptographickey/PredictableCryptographicKeyBBCase1.java
setErrorsCount("<example.predictablecryptographickey.PredictableCryptographicKeyBBCase1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablecryptographickey/PredictableCryptographicKeyABHCase2.java
setErrorsCount("<example.predictablecryptographickey.PredictableCryptographicKeyABHCase2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablecryptographickey/PredictableCryptographicKeyABICase2.java
setErrorsCount("<example.predictablecryptographickey.PredictableCryptographicKeyABICase2: void go()>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void predictableKeyStorePasswordExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/predictablekeystorepassword").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablekeystorepassword/PredictableKeyStorePasswordABICase1.java
setErrorsCount("<example.predictablekeystorepassword.PredictableKeyStorePasswordABICase1: void go(java.lang.String)>", HardCodedError.class, 1);
setErrorsCount("<example.predictablekeystorepassword.PredictableKeyStorePasswordABICase1: void go(java.lang.String)>", NeverTypeOfError.class, 1);
// ABH1, ABI2, BB1 are other similar test cases that were not included
scanner.exec();
assertErrors();
}
@Test
public void predictablePBEPasswordExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/predictablepbepassword").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablepbepassword/PredictablePBEPasswordBBCase2.java
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordBBCase2: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordBBCase2: void key()>", HardCodedError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablepbepassword/PredictablePBEPasswordABHCase2.java
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordABHCase2: void key(java.lang.String)>", NeverTypeOfError.class, 1);
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordABHCase2: void key(java.lang.String)>", HardCodedError.class, 1);
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordABHCase2: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/predictablepbepassword/PredictablePBEPasswordABICase1.java
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordABICase1: void key(java.lang.String)>", NeverTypeOfError.class, 1);
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordABICase1: void key(java.lang.String)>", HardCodedError.class, 1);
setErrorsCount("<example.predictablepbepassword.PredictablePBEPasswordABICase1: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// ABHCase1, BBCase1 are similar to the case above
scanner.exec();
assertErrors();
}
// Headless test cases regarding the CryptoGuard projects `predictableseeds`
// were not added due to the misuses not being caught by the analysis.
// The projects are CryptoGuard projects are found in the link below:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/tree/master/src/main/java/org/cryptoapi/bench/predictableseeds
// For the misuse an issue is opened and can be found in the link below:
// https://github.com/CROSSINGTUD/CryptoAnalysis/issues/140
@Test
public void staticInitializationVectorExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/staticinitializationvector").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticinitializationvector/StaticInitializationVectorABHCase1.java
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABHCase1: void go()>", IncompleteOperationError.class, 1);
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABHCase1: void go()>", RequiredPredicateError.class, 2);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticinitializationvector/StaticInitializationVectorABHCase2.java
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABHCase2: void go()>", IncompleteOperationError.class, 1);
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABHCase2: void go()>", RequiredPredicateError.class, 2);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticinitializationvector/StaticInitializationVectorABICase1.java
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABICase1: void go(javax.crypto.spec.IvParameterSpec)>", IncompleteOperationError.class, 1);
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABICase1: void go(javax.crypto.spec.IvParameterSpec)>", RequiredPredicateError.class, 1);
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABICase1: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticinitializationvector/StaticInitializationVectorABICase2.java
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABICase2: void go(javax.crypto.spec.IvParameterSpec)>", IncompleteOperationError.class, 1);
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABICase2: void go(javax.crypto.spec.IvParameterSpec)>", RequiredPredicateError.class, 1);
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorABICase2: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticinitializationvector/StaticInitializationVectorBBCase1.java
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorBBCase1: void go()>", RequiredPredicateError.class, 2);
setErrorsCount("<example.staticinitializationvector.StaticInitializationVectorBBCase1: void go()>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void staticSaltsExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoGuardExamples/staticsalts").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticsalts/StaticSaltsABHCase1.java
setErrorsCount("<example.staticsalts.StaticSaltsABHCase1: void key2()>", ConstraintError.class, 1);
setErrorsCount("<example.staticsalts.StaticSaltsABHCase1: void key2()>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticsalts/StaticSaltsABICase2.java
setErrorsCount("<example.staticsalts.StaticSaltsABICase2: void key2(int)>", ConstraintError.class, 1);
setErrorsCount("<example.staticsalts.StaticSaltsABICase2: void key2(int)>", RequiredPredicateError.class, 1);
// This test case corresponds to the following project in CryptoGuard:
// https://github.com/CryptoGuardOSS/cryptoapi-bench/blob/master/src/main/java/org/cryptoapi/bench/staticsalts/StaticSaltsBBCase1.java
setErrorsCount("<example.staticsalts.StaticSaltsBBCase1: void key2()>", ConstraintError.class, 1);
setErrorsCount("<example.staticsalts.StaticSaltsBBCase1: void key2()>", RequiredPredicateError.class, 1);
// ABICase1 is similar to the examples above
scanner.exec();
assertErrors();
}
}
| 23,954 | 71.81155 | 250 | java |