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 |
---|---|---|---|---|---|---|
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/SendReq.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import android.util.Log;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class SendReq extends MultimediaMessagePdu {
private static final String TAG = "SendReq";
public SendReq() {
super();
try {
setMessageType(PduHeaders.MESSAGE_TYPE_SEND_REQ);
setMmsVersion(PduHeaders.CURRENT_MMS_VERSION);
// FIXME: Content-type must be decided according to whether
// SMIL part present.
setContentType("application/vnd.wap.multipart.related".getBytes());
setFrom(new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()));
setTransactionId(generateTransactionId());
} catch (InvalidHeaderValueException e) {
// Impossible to reach here since all headers we set above are valid.
Log.e(TAG, "Unexpected InvalidHeaderValueException.", e);
throw new RuntimeException(e);
}
}
private byte[] generateTransactionId() {
String transactionId = "T" + Long.toHexString(System.currentTimeMillis());
return transactionId.getBytes();
}
/**
* Constructor, used when composing a M-Send.req pdu.
*
* @param contentType the content type value
* @param from the from value
* @param mmsVersion current viersion of mms
* @param transactionId the transaction-id value
* @throws InvalidHeaderValueException if parameters are invalid.
* NullPointerException if contentType, form or transactionId is null.
*/
public SendReq(byte[] contentType,
EncodedStringValue from,
int mmsVersion,
byte[] transactionId) throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_SEND_REQ);
setContentType(contentType);
setFrom(from);
setMmsVersion(mmsVersion);
setTransactionId(transactionId);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
SendReq(PduHeaders headers) {
super(headers);
}
/**
* Constructor with given headers and body
*
* @param headers Headers for this PDU.
* @param body Body of this PDu.
*/
public SendReq(PduHeaders headers, PduBody body) {
super(headers, body);
}
/**
* Get Bcc value.
*
* @return the value
*/
public EncodedStringValue[] getBcc() {
return mPduHeaders.getEncodedStringValues(PduHeaders.BCC);
}
/**
* Add a "BCC" value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void addBcc(EncodedStringValue value) {
mPduHeaders.appendEncodedStringValue(value, PduHeaders.BCC);
}
/**
* Set "BCC" value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setBcc(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.BCC);
}
/**
* Get CC value.
*
* @return the value
*/
public EncodedStringValue[] getCc() {
return mPduHeaders.getEncodedStringValues(PduHeaders.CC);
}
/**
* Add a "CC" value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void addCc(EncodedStringValue value) {
mPduHeaders.appendEncodedStringValue(value, PduHeaders.CC);
}
/**
* Set "CC" value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setCc(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.CC);
}
/**
* Get Content-type value.
*
* @return the value
*/
public byte[] getContentType() {
return mPduHeaders.getTextString(PduHeaders.CONTENT_TYPE);
}
/**
* Set Content-type value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setContentType(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.CONTENT_TYPE);
}
/**
* Get X-Mms-Delivery-Report value.
*
* @return the value
*/
public int getDeliveryReport() {
return mPduHeaders.getOctet(PduHeaders.DELIVERY_REPORT);
}
/**
* Set X-Mms-Delivery-Report value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setDeliveryReport(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.DELIVERY_REPORT);
}
/**
* Get X-Mms-Expiry value.
*
* Expiry-value = Value-length
* (Absolute-token Date-value | Relative-token Delta-seconds-value)
*
* @return the value
*/
public long getExpiry() {
return mPduHeaders.getLongInteger(PduHeaders.EXPIRY);
}
/**
* Set X-Mms-Expiry value.
*
* @param value the value
*/
public void setExpiry(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.EXPIRY);
}
/**
* Get X-Mms-MessageSize value.
*
* Expiry-value = size of message
*
* @return the value
*/
public long getMessageSize() {
return mPduHeaders.getLongInteger(PduHeaders.MESSAGE_SIZE);
}
/**
* Set X-Mms-MessageSize value.
*
* @param value the value
*/
public void setMessageSize(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.MESSAGE_SIZE);
}
/**
* Get X-Mms-Message-Class value.
* Message-class-value = Class-identifier | Token-text
* Class-identifier = Personal | Advertisement | Informational | Auto
*
* @return the value
*/
public byte[] getMessageClass() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_CLASS);
}
/**
* Set X-Mms-Message-Class value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageClass(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_CLASS);
}
/**
* Get X-Mms-Read-Report value.
*
* @return the value
*/
public int getReadReport() {
return mPduHeaders.getOctet(PduHeaders.READ_REPORT);
}
/**
* Set X-Mms-Read-Report value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReadReport(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.READ_REPORT);
}
/**
* Set "To" value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTo(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.TO);
}
/**
* Get X-Mms-Transaction-Id field value.
*
* @return the X-Mms-Report-Allowed value
*/
public byte[] getTransactionId() {
return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID);
}
/**
* Set X-Mms-Transaction-Id field value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTransactionId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID);
}
/*
* Optional, not supported header fields:
*
* public byte getAdaptationAllowed() {return 0};
* public void setAdaptationAllowed(btye value) {};
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte getContentClass() {return 0x00;}
* public void setApplicId(byte value) {}
*
* public long getDeliveryTime() {return 0};
* public void setDeliveryTime(long value) {};
*
* public byte getDrmContent() {return 0x00;}
* public void setDrmContent(byte value) {}
*
* public MmFlagsValue getMmFlags() {return null;}
* public void setMmFlags(MmFlagsValue value) {}
*
* public MmStateValue getMmState() {return null;}
* public void getMmState(MmStateValue value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*
* public byte getReplyCharging() {return 0x00;}
* public void setReplyCharging(byte value) {}
*
* public byte getReplyChargingDeadline() {return 0x00;}
* public void setReplyChargingDeadline(byte value) {}
*
* public byte[] getReplyChargingId() {return 0x00;}
* public void setReplyChargingId(byte[] value) {}
*
* public long getReplyChargingSize() {return 0;}
* public void setReplyChargingSize(long value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*
* public byte getStore() {return 0x00;}
* public void setStore(byte value) {}
*/
}
| 10,139 | 28.306358 | 97 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/androidTest/java/org/thoughtcrime/securesms/TextSecureTestCase.java | package org.thoughtcrime.securesms;
import android.content.Context;
import android.test.InstrumentationTestCase;
public class TextSecureTestCase extends InstrumentationTestCase {
@Override
public void setUp() throws Exception {
System.setProperty("dexmaker.dexcache", getInstrumentation().getTargetContext().getCacheDir().getPath());
}
protected Context getContext() {
return getInstrumentation().getContext();
}
}
| 437 | 24.764706 | 109 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/androidTest/java/org/thoughtcrime/securesms/database/AttachmentDatabaseTest.java | package org.thoughtcrime.securesms.database;
import android.net.Uri;
import org.thoughtcrime.securesms.TextSecureTestCase;
import org.thoughtcrime.securesms.attachments.AttachmentId;
import org.thoughtcrime.securesms.attachments.DatabaseAttachment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import java.io.FileNotFoundException;
import java.io.InputStream;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AttachmentDatabaseTest extends TextSecureTestCase {
private static final long ROW_ID = 1L;
private static final long UNIQUE_ID = 2L;
private AttachmentDatabase database;
@Override
public void setUp() {
database = spy(DatabaseFactory.getAttachmentDatabase(getInstrumentation().getTargetContext()));
}
public void testTaskNotRunWhenThumbnailExists() throws Exception {
final AttachmentId attachmentId = new AttachmentId(ROW_ID, UNIQUE_ID);
when(database.getAttachment(attachmentId)).thenReturn(getMockAttachment("x/x"));
doReturn(mock(InputStream.class)).when(database).getDataStream(any(MasterSecret.class), any(AttachmentId.class), eq("thumbnail"));
database.getThumbnailStream(mock(MasterSecret.class), attachmentId);
// XXX - I don't think this is testing anything? The thumbnail would be updated asynchronously.
verify(database, never()).updateAttachmentThumbnail(any(MasterSecret.class), any(AttachmentId.class), any(InputStream.class), anyFloat());
}
public void testTaskRunWhenThumbnailMissing() throws Exception {
final AttachmentId attachmentId = new AttachmentId(ROW_ID, UNIQUE_ID);
when(database.getAttachment(attachmentId)).thenReturn(getMockAttachment("image/png"));
doReturn(null).when(database).getDataStream(any(MasterSecret.class), any(AttachmentId.class), eq("thumbnail"));
doNothing().when(database).updateAttachmentThumbnail(any(MasterSecret.class), any(AttachmentId.class), any(InputStream.class), anyFloat());
try {
database.new ThumbnailFetchCallable(mock(MasterSecret.class), attachmentId).call();
throw new AssertionError("didn't try to generate thumbnail");
} catch (FileNotFoundException fnfe) {
// success
}
}
private DatabaseAttachment getMockAttachment(String contentType) {
DatabaseAttachment attachment = mock(DatabaseAttachment.class);
when(attachment.getContentType()).thenReturn(contentType);
when(attachment.getDataUri()).thenReturn(Uri.EMPTY);
return attachment;
}
}
| 2,834 | 39.5 | 143 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/androidTest/java/org/thoughtcrime/securesms/database/CanonicalAddressDatabaseTest.java | package org.thoughtcrime.securesms.database;
import org.thoughtcrime.securesms.TextSecureTestCase;
import static org.assertj.core.api.Assertions.assertThat;
public class CanonicalAddressDatabaseTest extends TextSecureTestCase {
private static final String AMBIGUOUS_NUMBER = "222-3333";
private static final String SPECIFIC_NUMBER = "+49 444 222 3333";
private static final String EMAIL = "[email protected]";
private static final String SIMILAR_EMAIL = "[email protected]";
private static final String GROUP = "__textsecure_group__!000111222333";
private static final String SIMILAR_GROUP = "__textsecure_group__!100111222333";
private static final String ALPHA = "T-Mobile";
private static final String SIMILAR_ALPHA = "T-Mobila";
private CanonicalAddressDatabase db;
public void setUp() throws Exception {
super.setUp();
this.db = CanonicalAddressDatabase.getInstance(getInstrumentation().getTargetContext());
}
public void tearDown() throws Exception {
}
/**
* Throw two equivalent numbers (one without locale info, one with full info) at the canonical
* address db and see that the caching and DB operations work properly in revealing the right
* addresses. This is run twice to ensure cache logic is hit.
*
* @throws Exception
*/
public void testNumberAddressUpdates() throws Exception {
final long id = db.getCanonicalAddressId(AMBIGUOUS_NUMBER);
assertThat(db.getAddressFromId(id)).isEqualTo(AMBIGUOUS_NUMBER);
assertThat(db.getCanonicalAddressId(SPECIFIC_NUMBER)).isEqualTo(id);
assertThat(db.getAddressFromId(id)).isEqualTo(SPECIFIC_NUMBER);
assertThat(db.getCanonicalAddressId(AMBIGUOUS_NUMBER)).isEqualTo(id);
assertThat(db.getCanonicalAddressId(AMBIGUOUS_NUMBER)).isEqualTo(id);
assertThat(db.getAddressFromId(id)).isEqualTo(AMBIGUOUS_NUMBER);
assertThat(db.getCanonicalAddressId(SPECIFIC_NUMBER)).isEqualTo(id);
assertThat(db.getAddressFromId(id)).isEqualTo(SPECIFIC_NUMBER);
assertThat(db.getCanonicalAddressId(AMBIGUOUS_NUMBER)).isEqualTo(id);
}
public void testSimilarNumbers() throws Exception {
assertThat(db.getCanonicalAddressId("This is a phone number 222-333-444"))
.isNotEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("222-333-444"))
.isNotEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("222-333-44"))
.isNotEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("222-333-4"))
.isNotEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("+49 222-333-4444"))
.isNotEqualTo(db.getCanonicalAddressId("+1 222-333-4444"));
assertThat(db.getCanonicalAddressId("1 222-333-4444"))
.isEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("1 (222) 333-4444"))
.isEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("+12223334444"))
.isEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("+1 (222) 333.4444"))
.isEqualTo(db.getCanonicalAddressId("222-333-4444"));
assertThat(db.getCanonicalAddressId("+49 (222) 333.4444"))
.isEqualTo(db.getCanonicalAddressId("222-333-4444"));
}
public void testEmailAddresses() throws Exception {
final long emailId = db.getCanonicalAddressId(EMAIL);
final long similarEmailId = db.getCanonicalAddressId(SIMILAR_EMAIL);
assertThat(emailId).isNotEqualTo(similarEmailId);
assertThat(db.getAddressFromId(emailId)).isEqualTo(EMAIL);
assertThat(db.getAddressFromId(similarEmailId)).isEqualTo(SIMILAR_EMAIL);
}
public void testGroups() throws Exception {
final long groupId = db.getCanonicalAddressId(GROUP);
final long similarGroupId = db.getCanonicalAddressId(SIMILAR_GROUP);
assertThat(groupId).isNotEqualTo(similarGroupId);
assertThat(db.getAddressFromId(groupId)).isEqualTo(GROUP);
assertThat(db.getAddressFromId(similarGroupId)).isEqualTo(SIMILAR_GROUP);
}
public void testAlpha() throws Exception {
final long id = db.getCanonicalAddressId(ALPHA);
final long similarId = db.getCanonicalAddressId(SIMILAR_ALPHA);
assertThat(id).isNotEqualTo(similarId);
assertThat(db.getAddressFromId(id)).isEqualTo(ALPHA);
assertThat(db.getAddressFromId(similarId)).isEqualTo(SIMILAR_ALPHA);
}
public void testIsNumber() throws Exception {
assertThat(CanonicalAddressDatabase.isNumberAddress("+495556666777")).isTrue();
assertThat(CanonicalAddressDatabase.isNumberAddress("(222) 333-4444")).isTrue();
assertThat(CanonicalAddressDatabase.isNumberAddress("1 (222) 333-4444")).isTrue();
assertThat(CanonicalAddressDatabase.isNumberAddress("T-Mobile123")).isTrue();
assertThat(CanonicalAddressDatabase.isNumberAddress("333-4444")).isTrue();
assertThat(CanonicalAddressDatabase.isNumberAddress("12345")).isTrue();
assertThat(CanonicalAddressDatabase.isNumberAddress("T-Mobile")).isFalse();
assertThat(CanonicalAddressDatabase.isNumberAddress("T-Mobile1")).isFalse();
assertThat(CanonicalAddressDatabase.isNumberAddress("Wherever bank")).isFalse();
assertThat(CanonicalAddressDatabase.isNumberAddress("__textsecure_group__!afafafafafaf")).isFalse();
assertThat(CanonicalAddressDatabase.isNumberAddress("[email protected]")).isFalse();
}
} | 5,520 | 45.788136 | 104 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/androidTest/java/org/thoughtcrime/securesms/jobs/CleanPreKeysJobTest.java | package org.thoughtcrime.securesms.jobs;
import org.thoughtcrime.securesms.TextSecureTestCase;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.dependencies.AxolotlStorageModule;
import org.whispersystems.libaxolotl.ecc.Curve;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyStore;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.push.SignedPreKeyEntity;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class CleanPreKeysJobTest extends TextSecureTestCase {
public void testSignedPreKeyRotationNotRegistered() throws IOException, MasterSecretJob.RequirementNotMetException {
TextSecureAccountManager accountManager = mock(TextSecureAccountManager.class);
SignedPreKeyStore signedPreKeyStore = mock(SignedPreKeyStore.class);
MasterSecret masterSecret = mock(MasterSecret.class);
when(accountManager.getSignedPreKey()).thenReturn(null);
CleanPreKeysJob cleanPreKeysJob = new CleanPreKeysJob(getContext());
ObjectGraph objectGraph = ObjectGraph.create(new TestModule(accountManager, signedPreKeyStore));
objectGraph.inject(cleanPreKeysJob);
cleanPreKeysJob.onRun(masterSecret);
verify(accountManager).getSignedPreKey();
verifyNoMoreInteractions(signedPreKeyStore);
}
public void testSignedPreKeyEviction() throws Exception {
SignedPreKeyStore signedPreKeyStore = mock(SignedPreKeyStore.class);
TextSecureAccountManager accountManager = mock(TextSecureAccountManager.class);
SignedPreKeyEntity currentSignedPreKeyEntity = mock(SignedPreKeyEntity.class);
MasterSecret masterSecret = mock(MasterSecret.class);
when(currentSignedPreKeyEntity.getKeyId()).thenReturn(3133);
when(accountManager.getSignedPreKey()).thenReturn(currentSignedPreKeyEntity);
final SignedPreKeyRecord currentRecord = new SignedPreKeyRecord(3133, System.currentTimeMillis(), Curve.generateKeyPair(), new byte[64]);
List<SignedPreKeyRecord> records = new LinkedList<SignedPreKeyRecord>() {{
add(new SignedPreKeyRecord(2, 11, Curve.generateKeyPair(), new byte[32]));
add(new SignedPreKeyRecord(4, System.currentTimeMillis() - 100, Curve.generateKeyPair(), new byte[64]));
add(currentRecord);
add(new SignedPreKeyRecord(3, System.currentTimeMillis() - 90, Curve.generateKeyPair(), new byte[64]));
add(new SignedPreKeyRecord(1, 10, Curve.generateKeyPair(), new byte[32]));
}};
when(signedPreKeyStore.loadSignedPreKeys()).thenReturn(records);
when(signedPreKeyStore.loadSignedPreKey(eq(3133))).thenReturn(currentRecord);
CleanPreKeysJob cleanPreKeysJob = new CleanPreKeysJob(getContext());
ObjectGraph objectGraph = ObjectGraph.create(new TestModule(accountManager, signedPreKeyStore));
objectGraph.inject(cleanPreKeysJob);
cleanPreKeysJob.onRun(masterSecret);
verify(signedPreKeyStore).removeSignedPreKey(eq(1));
verify(signedPreKeyStore, times(1)).removeSignedPreKey(anyInt());
}
public void testSignedPreKeyNoEviction() throws Exception {
SignedPreKeyStore signedPreKeyStore = mock(SignedPreKeyStore.class);
TextSecureAccountManager accountManager = mock(TextSecureAccountManager.class);
SignedPreKeyEntity currentSignedPreKeyEntity = mock(SignedPreKeyEntity.class);
when(currentSignedPreKeyEntity.getKeyId()).thenReturn(3133);
when(accountManager.getSignedPreKey()).thenReturn(currentSignedPreKeyEntity);
final SignedPreKeyRecord currentRecord = new SignedPreKeyRecord(3133, System.currentTimeMillis(), Curve.generateKeyPair(), new byte[64]);
List<SignedPreKeyRecord> records = new LinkedList<SignedPreKeyRecord>() {{
add(currentRecord);
}};
when(signedPreKeyStore.loadSignedPreKeys()).thenReturn(records);
when(signedPreKeyStore.loadSignedPreKey(eq(3133))).thenReturn(currentRecord);
CleanPreKeysJob cleanPreKeysJob = new CleanPreKeysJob(getContext());
ObjectGraph objectGraph = ObjectGraph.create(new TestModule(accountManager, signedPreKeyStore));
objectGraph.inject(cleanPreKeysJob);
verify(signedPreKeyStore, never()).removeSignedPreKey(anyInt());
}
public void testConnectionError() throws Exception {
SignedPreKeyStore signedPreKeyStore = mock(SignedPreKeyStore.class);
TextSecureAccountManager accountManager = mock(TextSecureAccountManager.class);
MasterSecret masterSecret = mock(MasterSecret.class);
when(accountManager.getSignedPreKey()).thenThrow(new PushNetworkException("Connectivity error!"));
CleanPreKeysJob cleanPreKeysJob = new CleanPreKeysJob(getContext());
ObjectGraph objectGraph = ObjectGraph.create(new TestModule(accountManager, signedPreKeyStore));
objectGraph.inject(cleanPreKeysJob);
try {
cleanPreKeysJob.onRun(masterSecret);
throw new AssertionError("should have failed!");
} catch (IOException e) {
assertTrue(cleanPreKeysJob.onShouldRetry(e));
}
}
@Module(injects = {CleanPreKeysJob.class})
public static class TestModule {
private final TextSecureAccountManager accountManager;
private final SignedPreKeyStore signedPreKeyStore;
private TestModule(TextSecureAccountManager accountManager, SignedPreKeyStore signedPreKeyStore) {
this.accountManager = accountManager;
this.signedPreKeyStore = signedPreKeyStore;
}
@Provides TextSecureAccountManager provideTextSecureAccountManager() {
return accountManager;
}
@Provides
AxolotlStorageModule.SignedPreKeyStoreFactory provideSignedPreKeyStore() {
return new AxolotlStorageModule.SignedPreKeyStoreFactory() {
@Override
public SignedPreKeyStore create() {
return signedPreKeyStore;
}
};
}
}
}
| 6,513 | 41.575163 | 141 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/androidTest/java/org/thoughtcrime/securesms/jobs/DeliveryReceiptJobTest.java | package org.thoughtcrime.securesms.jobs;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.thoughtcrime.securesms.TextSecureTestCase;
import org.whispersystems.textsecure.api.TextSecureMessageSender;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import org.whispersystems.textsecure.api.push.exceptions.NotFoundException;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.IOException;
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.thoughtcrime.securesms.dependencies.TextSecureCommunicationModule.TextSecureMessageSenderFactory;
public class DeliveryReceiptJobTest extends TextSecureTestCase {
public void testDelivery() throws IOException {
TextSecureMessageSender textSecureMessageSender = mock(TextSecureMessageSender.class);
long timestamp = System.currentTimeMillis();
DeliveryReceiptJob deliveryReceiptJob = new DeliveryReceiptJob(getContext(),
"+14152222222",
timestamp, "foo");
ObjectGraph objectGraph = ObjectGraph.create(new TestModule(textSecureMessageSender));
objectGraph.inject(deliveryReceiptJob);
deliveryReceiptJob.onRun();
ArgumentCaptor<TextSecureAddress> captor = ArgumentCaptor.forClass(TextSecureAddress.class);
verify(textSecureMessageSender).sendDeliveryReceipt(captor.capture(), eq(timestamp));
assertTrue(captor.getValue().getRelay().get().equals("foo"));
assertTrue(captor.getValue().getNumber().equals("+14152222222"));
}
public void testNetworkError() throws IOException {
TextSecureMessageSender textSecureMessageSender = mock(TextSecureMessageSender.class);
long timestamp = System.currentTimeMillis();
Mockito.doThrow(new PushNetworkException("network error"))
.when(textSecureMessageSender)
.sendDeliveryReceipt(any(TextSecureAddress.class), eq(timestamp));
DeliveryReceiptJob deliveryReceiptJob = new DeliveryReceiptJob(getContext(),
"+14152222222",
timestamp, "foo");
ObjectGraph objectGraph = ObjectGraph.create(new TestModule(textSecureMessageSender));
objectGraph.inject(deliveryReceiptJob);
try {
deliveryReceiptJob.onRun();
throw new AssertionError();
} catch (IOException e) {
assertTrue(deliveryReceiptJob.onShouldRetry(e));
}
Mockito.doThrow(new NotFoundException("not found"))
.when(textSecureMessageSender)
.sendDeliveryReceipt(any(TextSecureAddress.class), eq(timestamp));
try {
deliveryReceiptJob.onRun();
throw new AssertionError();
} catch (IOException e) {
assertFalse(deliveryReceiptJob.onShouldRetry(e));
}
}
@Module(injects = DeliveryReceiptJob.class)
public static class TestModule {
private final TextSecureMessageSender textSecureMessageSender;
public TestModule(TextSecureMessageSender textSecureMessageSender) {
this.textSecureMessageSender = textSecureMessageSender;
}
@Provides TextSecureMessageSenderFactory provideTextSecureMessageSenderFactory() {
return new TextSecureMessageSenderFactory() {
@Override
public TextSecureMessageSender create() {
return textSecureMessageSender;
}
};
}
}
}
| 3,761 | 36.62 | 115 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/androidTest/java/org/thoughtcrime/securesms/service/SmsListenerTest.java | /**
* Copyright (C) 2015 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms.service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import org.mockito.ArgumentCaptor;
import org.thoughtcrime.securesms.TextSecureTestCase;
import org.thoughtcrime.securesms.util.SmsUtil;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SmsListenerTest extends TextSecureTestCase {
private static final String CHALLENGE_SMS_3_3 = "Your TextSecure verification code: 337-337";
private static final String CHALLENGE_SMS_3_3_PREPEND = "XXX\nYour TextSecure verification code: 1337-1337";
private static final String CHALLENGE_SMS_3_4 = "Your TextSecure verification code: 337-1337";
private static final String CHALLENGE_SMS_4_3 = "Your TextSecure verification code: 1337-337";
private static final String CHALLENGE_SMS_4_4 = "Your TextSecure verification code: 1337-1337";
private static final String CHALLENGE_SMS_4_4_PREPEND = "XXXYour TextSecure verification code: 1337-1337";
private static final String CHALLENGE_SMS_4_4_APPEND = "Your TextSecure verification code: 1337-1337XXX";
private static final String[] CHALLENGE_SMS = {
CHALLENGE_SMS_3_3, CHALLENGE_SMS_3_3_PREPEND, CHALLENGE_SMS_3_4, CHALLENGE_SMS_4_3,
CHALLENGE_SMS_4_4, CHALLENGE_SMS_4_4_PREPEND, CHALLENGE_SMS_4_4_APPEND
};
private static final String CHALLENGE_3_3 = "337337";
private static final String CHALLENGE_3_4 = "3371337";
private static final String CHALLENGE_4_3 = "1337337";
private static final String CHALLENGE_4_4 = "13371337";
private static final String[] CHALLENGES = {
CHALLENGE_3_3, CHALLENGE_3_3, CHALLENGE_3_4, CHALLENGE_4_3,
CHALLENGE_4_4, CHALLENGE_4_4, CHALLENGE_4_4,
};
public void testReceiveChallenges() throws Exception {
final SmsListener smsListener = new SmsListener();
for (int i = 0; i < CHALLENGES.length; i++) {
final String CHALLENGE = CHALLENGES[i];
final String CHALLENGE_SMS = SmsListenerTest.CHALLENGE_SMS[i];
final Context mockContext = mock(Context.class);
final SharedPreferences mockPreferences = mock(SharedPreferences.class);
final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
when(mockContext.getPackageName()).thenReturn(getContext().getPackageName());
when(mockContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockPreferences);
when(mockPreferences.getBoolean(contains("pref_verifying"), anyBoolean())).thenReturn(true);
try {
smsListener.onReceive(mockContext, SmsUtil.buildSmsReceivedIntent("15555555555", (CHALLENGE_SMS)));
} catch (IllegalStateException e) {
Log.d(getClass().getName(), "some api levels are picky with abortBroadcast()");
}
verify(mockContext, times(1)).sendBroadcast(intentCaptor.capture());
final Intent sendIntent = intentCaptor.getValue();
assertTrue(sendIntent.getAction().equals(RegistrationService.CHALLENGE_EVENT));
assertTrue(sendIntent.getStringExtra(RegistrationService.CHALLENGE_EXTRA).equals(CHALLENGE));
}
}
}
| 4,194 | 45.611111 | 110 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/androidTest/java/org/thoughtcrime/securesms/util/SmsUtil.java | /*
* Copyright (C) 2015 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms.util;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.PhoneNumberUtils;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SmsUtil {
private static byte reverseByte(byte b) {
return (byte) ((b & 0xF0) >> 4 | (b & 0x0F) << 4);
}
/*
credit :D
http://stackoverflow.com/a/12338541
*/
@SuppressWarnings("unchecked")
public static byte[] buildSmsPdu(String senderPstnNumber, String body) throws Exception{
byte[] scBytes = PhoneNumberUtils.networkPortionToCalledPartyBCD("0000000000");
byte[] senderBytes = PhoneNumberUtils.networkPortionToCalledPartyBCD(senderPstnNumber);
int lsmcs = scBytes.length;
byte[] dateBytes = new byte[7];
Calendar calendar = new GregorianCalendar();
dateBytes[0] = reverseByte((byte) (calendar.get(Calendar.YEAR)));
dateBytes[1] = reverseByte((byte) (calendar.get(Calendar.MONTH) + 1));
dateBytes[2] = reverseByte((byte) (calendar.get(Calendar.DAY_OF_MONTH)));
dateBytes[3] = reverseByte((byte) (calendar.get(Calendar.HOUR_OF_DAY)));
dateBytes[4] = reverseByte((byte) (calendar.get(Calendar.MINUTE)));
dateBytes[5] = reverseByte((byte) (calendar.get(Calendar.SECOND)));
dateBytes[6] = reverseByte((byte) ((calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000 * 15)));
ByteArrayOutputStream bo = new ByteArrayOutputStream();
bo.write(lsmcs);
bo.write(scBytes);
bo.write(0x04);
bo.write((byte) senderPstnNumber.length());
bo.write(senderBytes);
bo.write(0x00);
bo.write(0x00);
bo.write(dateBytes);
String sReflectedClassName = "com.android.internal.telephony.GsmAlphabet";
Class cReflectedNFCExtras = Class.forName(sReflectedClassName);
Method stringToGsm7BitPacked = cReflectedNFCExtras.getMethod("stringToGsm7BitPacked", new Class[] { String.class });
stringToGsm7BitPacked.setAccessible(true);
byte[] bodybytes = (byte[]) stringToGsm7BitPacked.invoke(null, body);
bo.write(bodybytes);
return bo.toByteArray();
}
@SuppressLint("NewApi")
public static Intent buildSmsReceivedIntent(String senderPstnNumber, String smsBody) throws Exception {
final Intent smsIntent = mock(Intent.class);
final Bundle smsExtras = new Bundle();
final byte[] smsPdu = SmsUtil.buildSmsPdu(senderPstnNumber, smsBody);
smsExtras.putSerializable("pdus", new Object[]{smsPdu});
when(smsIntent.getAction()).thenReturn(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
when(smsIntent.getExtras()).thenReturn(smsExtras);
return smsIntent;
}
}
| 3,601 | 36.915789 | 133 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/BaseUnitTest.java | package org.thoughtcrime.securesms;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Log.class, Handler.class, Looper.class, TextUtils.class })
public abstract class BaseUnitTest {
protected Context context;
protected MasterSecret masterSecret;
@Before
public void setUp() throws Exception {
context = mock(Context.class);
masterSecret = new MasterSecret(new SecretKeySpec(new byte[16], "AES"),
new SecretKeySpec(new byte[16], "HmacSHA1"));
mockStatic(Looper.class);
mockStatic(Log.class);
mockStatic(Handler.class);
mockStatic(TextUtils.class);
when(Looper.getMainLooper()).thenReturn(null);
PowerMockito.whenNew(Handler.class).withAnyArguments().thenReturn(null);
Answer<?> logAnswer = new Answer<Void>() {
@Override public Void answer(InvocationOnMock invocation) throws Throwable {
final String tag = (String)invocation.getArguments()[0];
final String msg = (String)invocation.getArguments()[1];
System.out.println(invocation.getMethod().getName().toUpperCase() + "/[" + tag + "] " + msg);
return null;
}
};
PowerMockito.doAnswer(logAnswer).when(Log.class, "d", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "i", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "w", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "e", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "wtf", anyString(), anyString());
PowerMockito.doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
final String s = (String)invocation.getArguments()[0];
return s == null || s.length() == 0;
}
}).when(TextUtils.class, "isEmpty", anyString());
SharedPreferences mockSharedPreferences = mock(SharedPreferences.class);
when(mockSharedPreferences.getString(anyString(), anyString())).thenReturn("");
when(mockSharedPreferences.getLong(anyString(), anyLong())).thenReturn(0L);
when(mockSharedPreferences.getInt(anyString(), anyInt())).thenReturn(0);
when(mockSharedPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(false);
when(mockSharedPreferences.getFloat(anyString(), anyFloat())).thenReturn(0f);
when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(mockSharedPreferences);
}
}
| 3,612 | 42.011905 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/crypto/MasterCipherTest.java | package org.thoughtcrime.securesms.crypto;
import org.junit.Before;
import org.junit.Test;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.thoughtcrime.securesms.BaseUnitTest;
import org.whispersystems.libaxolotl.InvalidMessageException;
@PowerMockIgnore("javax.crypto.*")
public class MasterCipherTest extends BaseUnitTest {
private MasterCipher masterCipher;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
masterCipher = new MasterCipher(masterSecret);
}
@Test(expected = InvalidMessageException.class)
public void testEncryptBytesWithZeroBody() throws Exception {
masterCipher.decryptBytes(new byte[]{});
}
}
| 699 | 27 | 66 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/database/CursorRecyclerViewAdapterTest.java | package org.thoughtcrime.securesms.database;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.View;
import android.view.ViewGroup;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CursorRecyclerViewAdapterTest {
private CursorRecyclerViewAdapter adapter;
private Context context;
private Cursor cursor;
@Before
public void setUp() {
context = mock(Context.class);
cursor = mock(Cursor.class);
when(cursor.getCount()).thenReturn(100);
when(cursor.moveToPosition(anyInt())).thenReturn(true);
adapter = new CursorRecyclerViewAdapter(context, cursor) {
@Override
public ViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindItemViewHolder(ViewHolder viewHolder, @NonNull Cursor cursor) {
}
};
}
@Test
public void testSanityCount() throws Exception {
assertEquals(adapter.getItemCount(), 100);
}
@Test
public void testHeaderCount() throws Exception {
adapter.setHeaderView(new View(context));
assertEquals(adapter.getItemCount(), 101);
assertEquals(adapter.getItemViewType(0), CursorRecyclerViewAdapter.HEADER_TYPE);
assertNotEquals(adapter.getItemViewType(1), CursorRecyclerViewAdapter.HEADER_TYPE);
assertNotEquals(adapter.getItemViewType(100), CursorRecyclerViewAdapter.HEADER_TYPE);
}
@Test
public void testFooterCount() throws Exception {
adapter.setFooterView(new View(context));
assertEquals(adapter.getItemCount(), 101);
assertEquals(adapter.getItemViewType(100), CursorRecyclerViewAdapter.FOOTER_TYPE);
assertNotEquals(adapter.getItemViewType(0), CursorRecyclerViewAdapter.FOOTER_TYPE);
assertNotEquals(adapter.getItemViewType(99), CursorRecyclerViewAdapter.FOOTER_TYPE);
}
@Test
public void testHeaderFooterCount() throws Exception {
adapter.setHeaderView(new View(context));
adapter.setFooterView(new View(context));
assertEquals(adapter.getItemCount(), 102);
assertEquals(adapter.getItemViewType(101), CursorRecyclerViewAdapter.FOOTER_TYPE);
assertEquals(adapter.getItemViewType(0), CursorRecyclerViewAdapter.HEADER_TYPE);
assertNotEquals(adapter.getItemViewType(1), CursorRecyclerViewAdapter.HEADER_TYPE);
assertNotEquals(adapter.getItemViewType(100), CursorRecyclerViewAdapter.FOOTER_TYPE);
}
}
| 2,737 | 33.658228 | 89 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/jobs/AttachmentDownloadJobTest.java | package org.thoughtcrime.securesms.jobs;
import org.junit.Before;
import org.junit.Test;
import org.thoughtcrime.securesms.BaseUnitTest;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.attachments.AttachmentId;
import org.thoughtcrime.securesms.jobs.AttachmentDownloadJob.InvalidPartException;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
public class AttachmentDownloadJobTest extends BaseUnitTest {
private AttachmentDownloadJob job;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
job = new AttachmentDownloadJob(context, 1L, new AttachmentId(1L, 1L));
}
@Test(expected = InvalidPartException.class)
public void testCreateAttachmentPointerInvalidId() throws Exception {
Attachment attachment = mock(Attachment.class);
when(attachment.getLocation()).thenReturn(null);
when(attachment.getKey()).thenReturn("a long and acceptable valid key like we all want");
job.createAttachmentPointer(masterSecret, attachment);
}
@Test(expected = InvalidPartException.class)
public void testCreateAttachmentPointerInvalidKey() throws Exception {
Attachment attachment = mock(Attachment.class);
when(attachment.getLocation()).thenReturn("something");
when(attachment.getKey()).thenReturn(null);
job.createAttachmentPointer(masterSecret, attachment);
}
}
| 1,432 | 33.95122 | 93 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/util/ListPartitionTest.java | package org.thoughtcrime.securesms.util;
import org.junit.Test;
import org.thoughtcrime.securesms.BaseUnitTest;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ListPartitionTest extends BaseUnitTest {
@Test public void testPartitionEven() {
List<Integer> list = new LinkedList<>();
for (int i=0;i<100;i++) {
list.add(i);
}
List<List<Integer>> partitions = Util.partition(list, 10);
assertEquals(partitions.size(), 10);
int counter = 0;
for (int i=0;i<partitions.size();i++) {
List<Integer> partition = partitions.get(i);
assertEquals(partition.size(), 10);
for (int j=0;j<partition.size();j++) {
assertEquals((int)partition.get(j), counter++);
}
}
}
@Test public void testPartitionOdd() {
List<Integer> list = new LinkedList<>();
for (int i=0;i<100;i++) {
list.add(i);
}
list.add(100);
List<List<Integer>> partitions = Util.partition(list, 10);
assertEquals(partitions.size(), 11);
int counter = 0;
for (int i=0;i<partitions.size()-1;i++) {
List<Integer> partition = partitions.get(i);
assertEquals(partition.size(), 10);
for (int j=0;j<partition.size();j++) {
assertEquals((int)partition.get(j), counter++);
}
}
assertEquals(partitions.get(10).size(), 1);
assertEquals((int)partitions.get(10).get(0), 100);
}
@Test public void testPathological() {
List<Integer> list = new LinkedList<>();
for (int i=0;i<100;i++) {
list.add(i);
}
List<List<Integer>> partitions = Util.partition(list, 1);
assertEquals(partitions.size(), 100);
int counter = 0;
for (int i=0;i<partitions.size();i++) {
List<Integer> partition = partitions.get(i);
assertEquals(partition.size(), 1);
for (int j=0;j<partition.size();j++) {
assertEquals((int)partition.get(j), counter++);
}
}
}
}
| 1,982 | 21.793103 | 62 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/util/PhoneNumberFormatterTest.java | package org.thoughtcrime.securesms.util;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
import static org.assertj.core.api.Assertions.assertThat;
public class PhoneNumberFormatterTest {
private static final String LOCAL_NUMBER = "+15555555555";
@Test public void testFormatNumberE164() throws Exception, InvalidNumberException {
assertThat(PhoneNumberFormatter.formatNumber("(555) 555-5555", LOCAL_NUMBER)).isEqualTo(LOCAL_NUMBER);
assertThat(PhoneNumberFormatter.formatNumber("555-5555", LOCAL_NUMBER)).isEqualTo(LOCAL_NUMBER);
assertThat(PhoneNumberFormatter.formatNumber("(123) 555-5555", LOCAL_NUMBER)).isNotEqualTo(LOCAL_NUMBER);
}
@Test public void testFormatNumberEmail() throws Exception {
try {
PhoneNumberFormatter.formatNumber("[email protected]", LOCAL_NUMBER);
throw new AssertionFailedError("should have thrown on email");
} catch (InvalidNumberException ine) {
// success
}
}
}
| 1,110 | 37.310345 | 109 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/util/Rfc5724UriTest.java | /*
* Copyright (C) 2015 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms.util;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import org.thoughtcrime.securesms.BaseUnitTest;
import java.net.URISyntaxException;
import static org.junit.Assert.assertTrue;
public class Rfc5724UriTest extends BaseUnitTest {
@Test public void testInvalidPath() throws Exception {
final String[] invalidSchemaUris = {
"",
":",
"sms:",
":sms",
"sms:?goto=fail",
"sms:?goto=fail&fail=goto"
};
for (String uri : invalidSchemaUris) {
try {
new Rfc5724Uri(uri);
throw new AssertionFailedError("URISyntaxException should be thrown");
} catch (URISyntaxException e) {
// success
}
}
}
@Test public void testGetSchema() throws Exception {
final String[][] uriTestPairs = {
{"sms:+15555555555", "sms"},
{"sMs:+15555555555", "sMs"},
{"smsto:+15555555555?", "smsto"},
{"mms:+15555555555?a=b", "mms"},
{"mmsto:+15555555555?a=b&c=d", "mmsto"}
};
for (String[] uriTestPair : uriTestPairs) {
final Rfc5724Uri testUri = new Rfc5724Uri(uriTestPair[0]);
assertTrue(testUri.getSchema().equals(uriTestPair[1]));
}
}
@Test public void testGetPath() throws Exception {
final String[][] uriTestPairs = {
{"sms:+15555555555", "+15555555555"},
{"sms:%2B555555555", "%2B555555555"},
{"smsto:+15555555555?", "+15555555555"},
{"mms:+15555555555?a=b", "+15555555555"},
{"mmsto:+15555555555?a=b&c=d", "+15555555555"},
{"sms:+15555555555,+14444444444", "+15555555555,+14444444444"},
{"sms:+15555555555,+14444444444?", "+15555555555,+14444444444"},
{"sms:+15555555555,+14444444444?a=b", "+15555555555,+14444444444"},
{"sms:+15555555555,+14444444444?a=b&c=d", "+15555555555,+14444444444"}
};
for (String[] uriTestPair : uriTestPairs) {
final Rfc5724Uri testUri = new Rfc5724Uri(uriTestPair[0]);
assertTrue(testUri.getPath().equals(uriTestPair[1]));
}
}
@Test public void testGetQueryParams() throws Exception {
final String[][] uriTestPairs = {
{"sms:+15555555555", "a", null},
{"mms:+15555555555?b=", "a", null},
{"mmsto:+15555555555?a=", "a", ""},
{"sms:+15555555555?a=b", "a", "b"},
{"sms:+15555555555?a=b&c=d", "a", "b"},
{"sms:+15555555555?a=b&c=d", "b", null},
{"sms:+15555555555?a=b&c=d", "c", "d"},
{"sms:+15555555555?a=b&c=d", "d", null}
};
for (String[] uriTestPair : uriTestPairs) {
final Rfc5724Uri testUri = new Rfc5724Uri(uriTestPair[0]);
final String paramResult = testUri.getQueryParams().get(uriTestPair[1]);
if (paramResult == null) assertTrue(uriTestPair[2] == null);
else assertTrue(paramResult.equals(uriTestPair[2]));
}
}
}
| 3,768 | 34.556604 | 82 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/test/unitTest/java/org/thoughtcrime/securesms/util/ShortCodeUtilTest.java | package org.thoughtcrime.securesms.util;
import org.junit.Test;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class ShortCodeUtilTest {
@Test
public void testShortCodes() throws Exception {
assertTrue(ShortCodeUtil.isShortCode("+14152222222", "40404"));
assertTrue(ShortCodeUtil.isShortCode("+14152222222", "431"));
assertFalse(ShortCodeUtil.isShortCode("+14152222222", "4157778888"));
assertFalse(ShortCodeUtil.isShortCode("+14152222222", "+14157778888"));
assertFalse(ShortCodeUtil.isShortCode("+14152222222", "415-777-8888"));
assertFalse(ShortCodeUtil.isShortCode("+14152222222", "(415) 777-8888"));
assertFalse(ShortCodeUtil.isShortCode("+14152222222", "8882222"));
assertFalse(ShortCodeUtil.isShortCode("+14152222222", "888-2222"));
assertTrue(ShortCodeUtil.isShortCode("+491723742522", "670"));
assertTrue(ShortCodeUtil.isShortCode("+491723742522", "115"));
assertFalse(ShortCodeUtil.isShortCode("+491723742522", "089-12345678"));
assertFalse(ShortCodeUtil.isShortCode("+491723742522", "089/12345678"));
assertFalse(ShortCodeUtil.isShortCode("+491723742522", "12345678"));
assertTrue(ShortCodeUtil.isShortCode("+298123456", "4040"));
assertTrue(ShortCodeUtil.isShortCode("+298123456", "6701"));
assertTrue(ShortCodeUtil.isShortCode("+298123456", "433"));
assertFalse(ShortCodeUtil.isShortCode("+298123456", "123456"));
assertTrue(ShortCodeUtil.isShortCode("+61414915066", "19808948"));
assertFalse(ShortCodeUtil.isShortCode("+61414915066", "119808948"));
assertTrue(ShortCodeUtil.isShortCode("+79166503388", "8080"));
assertTrue(ShortCodeUtil.isShortCode("+79166503388", "6701"));
assertTrue(ShortCodeUtil.isShortCode("+79166503388", "431"));
assertFalse(ShortCodeUtil.isShortCode("+79166503388", "111-22-33"));
}
}
| 1,890 | 44.02381 | 77 | java |
cryptoguard | cryptoguard-master/samples/Crypto_Example/src/main/java/Crypto.java | import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Random;
/**
* Created by krishnokoli on 7/2/17.
*
* @author krishnokoli
* @since V01.00
*/
public class Crypto {
private static String AES_ECB = "AES/ECB/PKCS5PADDING";
public static Cipher cipher;
public void Crypto(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec1 = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher = Cipher.getInstance(AES_ECB);
long currentTime = System.nanoTime();
String currentTimeStr = String.valueOf(currentTime);
SecretKeySpec secretKeySpec = new SecretKeySpec(currentTimeStr.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
cipher.init(Cipher.DECRYPT_MODE, skeySpec1, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ DatatypeConverter.printBase64Binary(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static TrustManager getTrustManager() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
return defaultHostnameVerifier.verify("*.amap.com", sslSession);
}
};
HostnameVerifier hostnameVerifier1 = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
System.out.println(hostnameVerifier);
TrustManager ignoreValidationTM = new X509TrustManager() {
private X509TrustManager trustManager;
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
if (x509CertificateArr == null || x509CertificateArr.length != 1) {
this.trustManager.checkServerTrusted(x509CertificateArr, str);
} else {
x509CertificateArr[0].checkValidity();
}
}
};
return ignoreValidationTM;
}
public KeyPair generateKeyPair() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.setKeyEntry(null, null, "mypass".toCharArray(), null);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, new SecureRandom());
return keyPairGenerator.genKeyPair();
}
public KeyPair generateKeyPairDefaultKeySize() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.setKeyEntry(null, null, "mypass".toCharArray(), null);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
return keyPairGenerator.genKeyPair();
}
public void geCustomSocketFactory() throws IOException {
SocketFactory sf = SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) sf.createSocket("gmail.com", 443);
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSession s = socket.getSession();
// Verify that the certicate hostname is for mail.google.com
// This is due to lack of SNI support in the current SSLSocket.
if (!hv.verify("mail.google.com", s)) {
throw new SSLHandshakeException("Expected mail.google.com, not found " + s.getPeerPrincipal());
}
socket.close();
}
public static byte[] randomNumberGeneration(long seed) {
byte[] randomBytes = new byte[64];
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(seed);
secureRandom.nextBytes(randomBytes);
return randomBytes;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String key = "Bar12345Bar12345"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
MessageDigest md = MessageDigest.getInstance("SHA1");
MessageDigest md2 = MessageDigest.getInstance("SHA");
TrustManager trustManager = getTrustManager();
System.out.println(trustManager);
System.out.println(md.toString() + md2);
// decrypt(key, initVector, "abcd");
randomNumberGeneration(1000L);
//
while (args.length > 0) {
if (args[0].equals("g")) {
decrypt(key, initVector, "abcd");
}
}
System.out.println("Hello World");
}
}
| 6,253 | 32.98913 | 138 | java |
cryptoguard | cryptoguard-master/samples/PBEUsage_Example/src/main/java/PBEUsage.java | import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by krishnokoli on 11/15/17.
*
*
* @author krishnokoli
* @since V01.00
*/
public class PBEUsage {
private static final String MK_CIPHER = "AES";
private static final int MK_KeySize = 256;
private static final int SALT_SIZE = 8;
private static final String PBE_ALGO = "PBEWithMD5AndTripleDES";
private static final String MD_ALGO = "MD5";
private static byte[] encryptMasterKey(String password) throws Throwable {
Key secretKey = generateMasterKey();
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey.getEncoded(), pbeKeySpec);
return masterKeyToDB;
}
private static byte[] encryptMasterKey(String password, byte[] secretKey) throws Throwable {
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey, pbeKeySpec);
return masterKeyToDB;
}
private static Key generateMasterKey() throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance(MK_CIPHER);
kg.init(MK_KeySize);
return kg.generateKey();
}
private static PBEKeySpec getPBEParameterSpec(String password) throws Throwable {
MessageDigest md = MessageDigest.getInstance(MD_ALGO);
byte[] saltGen = md.digest(password.getBytes());
byte[] salt = new byte[SALT_SIZE];
System.arraycopy(saltGen, 0, salt, 0, SALT_SIZE);
int iteration = password.toCharArray().length + 1;
return new PBEKeySpec(password.toCharArray(), salt, iteration);
}
private static byte[] encryptKey(byte[] data, PBEKeySpec keyspec) throws Throwable {
SecretKey key = getPasswordKey(keyspec);
if(keyspec.getSalt() != null) {
PBEParameterSpec paramSpec = new PBEParameterSpec(keyspec.getSalt(), keyspec.getIterationCount());
Cipher c = Cipher.getInstance(key.getAlgorithm());
c.init(Cipher.ENCRYPT_MODE, key,paramSpec);
return c.doFinal(data);
}
return null;
}
private static SecretKey getPasswordKey(PBEKeySpec keyspec) throws Throwable {
SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGO);
return factory.generateSecret(keyspec);
}
public static void main(String[] args) {
try {
byte[] output = encryptMasterKey("ChangeBeforeProd");
System.out.println(output);
} catch (Throwable e) {
System.out.println("Hit an exception encrypting the master key");
}
System.out.println("Hello World");
}
}
| 2,891 | 36.076923 | 110 | java |
cryptoguard | cryptoguard-master/samples/PasswordUtils_Example/src/main/java/PasswordUtils.java | import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.Map;
/**
* Created by krishnokoli on 11/27/17.
*
* @author krishnokoli
* @since V01.00
*/
public class PasswordUtils {
private final String CRYPT_ALGO;
private String password;
private final char[] ENCRYPT_KEY;
private final byte[] SALT;
private final int ITERATION_COUNT;
private final char[] encryptKey;
private final byte[] salt;
private static final String LEN_SEPARATOR_STR = ":";
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static final String DEFAULT_ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV";
public static final String DEFAULT_SALT = "f77aLYLo";
public static final int DEFAULT_ITERATION_COUNT = 17;
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
private String encrypt() throws IOException {
String ret = null;
String strToEncrypt = null;
if (password == null) {
strToEncrypt = "";
} else {
strToEncrypt = password.length() + LEN_SEPARATOR_STR + password;
}
try {
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes());
ret = new String(DatatypeConverter.printBase64Binary(encryptedStr));
} catch (Throwable t) {
throw new IOException("Unable to encrypt password due to error", t);
}
return ret;
}
PasswordUtils(String aPassword) {
String[] crypt_algo_array = null;
int count = 0;
if (aPassword != null && aPassword.contains(",")) {
count = aPassword.split(",").length;
crypt_algo_array = aPassword.split(",");
}
if (crypt_algo_array != null && crypt_algo_array.length > 1) {
CRYPT_ALGO = crypt_algo_array[0];
ENCRYPT_KEY = crypt_algo_array[1].toCharArray();
SALT = crypt_algo_array[2].getBytes();
ITERATION_COUNT = Integer.parseInt(crypt_algo_array[3]);
password = crypt_algo_array[4];
if (count > 4) {
for (int i = 5; i <= count; i++) {
password = password + "," + crypt_algo_array[i];
}
}
} else {
CRYPT_ALGO = DEFAULT_CRYPT_ALGO;
ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
SALT = DEFAULT_SALT.getBytes();
ITERATION_COUNT = DEFAULT_ITERATION_COUNT;
password = aPassword;
}
Map<String, String> env = System.getenv();
String encryptKeyStr = env.get("ENCRYPT_KEY");
if (encryptKeyStr == null) {
encryptKey = ENCRYPT_KEY;
} else {
encryptKey = encryptKeyStr.toCharArray();
}
String saltStr = env.get("ENCRYPT_SALT");
if (saltStr == null) {
salt = SALT;
} else {
salt = saltStr.getBytes();
}
}
public static String decryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword)
.decrypt();
}
private String decrypt() throws IOException {
String ret = null;
try {
byte[] decodedPassword = DatatypeConverter.parseBase64Binary(password);
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
String decrypted = new String(engine.doFinal(decodedPassword));
int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR);
if (foundAt > -1) {
if (decrypted.length() > foundAt) {
ret = decrypted.substring(foundAt + 1);
} else {
ret = "";
}
} else {
ret = null;
}
} catch (Throwable t) {
throw new IOException("Unable to decrypt password due to error", t);
}
return ret;
}
public static void main(String[] args) {
try {
decryptPassword("helloworld");
} catch (Exception e) {
System.out.println("Hit an issue decrypting a password");
}
System.out.println("Hello World");
}
}
| 5,053 | 35.1 | 102 | java |
cryptoguard | cryptoguard-master/samples/SymCrypto_Example/src/main/java/SymCrypto.java | import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class SymCrypto {
private static String ALGO = "AES";
private static String ALGO_SPEC = "AES/CBC/NoPadding";
private static String defaultKey;
private static Cipher cipher;
private static KeyGenerator keyGenerator;
public static byte[] encrypt(String txt, String key) throws Exception {
if (key == null) {
key = new String(defaultKey);
} else if (key.isEmpty()) {
key = getKey();
}
byte[] keyBytes = DatatypeConverter.parseBase64Binary(key);
byte[] txtBytes = txt.getBytes();
SecretKeySpec keySpc = new SecretKeySpec(keyBytes, ALGO);
cipher.init(Cipher.ENCRYPT_MODE, keySpc);
return cipher.doFinal(txtBytes);
}
private static String getKey() {
return getKeyInternal();
}
private static String getKeyInternal(){
return "xyzzzzzzzzzzzzzzzzzzzzzz";
}
public static String getKey(String src) {
String val = System.getProperty(src);
if (val == null) {
val = new String("defalultval");
}
return val;
}
public static void main(String[] args) {
String key = "testKey";
try {
cipher = Cipher.getInstance(ALGO_SPEC);
keyGenerator = KeyGenerator.getInstance(ALGO);
String keyStr = getKey(key);
if (keyStr == null) {
byte[] keyBytes = new byte[12];
keyBytes[0] = 0;
keyBytes[1] = 1;
defaultKey = new String(keyBytes);
} else {
defaultKey = keyStr;
}
byte[] encryption = encrypt("Hello World",keyStr);
} catch (Exception e) {
System.out.println("Issue happend");
}
System.out.println("Hello World");
}
}
| 1,818 | 23.581081 | 75 | java |
cryptoguard | cryptoguard-master/samples/SymCrypto_Multi_Example/src/main/java/PassEncryptor.java | public class PassEncryptor {
private SymCrypto symCrypto;
private String passKey = "pass.key";
private static final String prefix = "{key}";
public PassEncryptor() throws Exception {
symCrypto = new SymCrypto(passKey, prefix.length());
}
byte[] encPass(String pass, String src) throws Exception {
return symCrypto.encrypt(pass, "hardcoded");
}
public static void main(String[] args) {
System.out.println("Hello World");
}
}
| 499 | 21.727273 | 62 | java |
cryptoguard | cryptoguard-master/samples/SymCrypto_Multi_Example/src/main/java/SymCrypto.java | import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class SymCrypto {
private String ALGO = "AES";
private String ALGO_SPEC = "AES/CBC/NoPadding";
private String defaultKey;
private Cipher cipher;
private KeyGenerator keyGenerator;
public SymCrypto(String key, int size) throws Exception {
cipher = Cipher.getInstance(ALGO_SPEC);
keyGenerator = KeyGenerator.getInstance(ALGO);
String keyStr = getKey(key);
if (keyStr == null) {
byte[] keyBytes = new byte[12];
keyBytes[0] = 0;
keyBytes[1] = 1;
defaultKey = new String(keyBytes);
} else {
defaultKey = keyStr;
}
}
public byte[] encrypt(String txt, String key) throws Exception {
if (key == null) {
key = new String(defaultKey);
} else if (key.isEmpty()) {
key = getKey();
}
byte[] keyBytes = DatatypeConverter.parseBase64Binary(key);
byte[] txtBytes = txt.getBytes();
SecretKeySpec keySpc = new SecretKeySpec(keyBytes, ALGO);
cipher.init(Cipher.ENCRYPT_MODE, keySpc);
return cipher.doFinal(txtBytes);
}
private String getKey() {
return getKeyInternal();
}
private String getKeyInternal(){
return "xyzzzzzzzzzzzzzzzzzzzzzz";
}
public String getKey(String src) {
String val = System.getProperty(src);
if (val == null) {
val = new String("defalultval");
}
return val;
}
}
| 1,647 | 24.353846 | 68 | java |
cryptoguard | cryptoguard-master/samples/SymCrypto_Package_Example/src/main/java/tester/SymCrypto.java | package tester;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class SymCrypto {
private static String ALGO = "AES";
private static String ALGO_SPEC = "AES/CBC/NoPadding";
private static String defaultKey;
private static Cipher cipher;
private static KeyGenerator keyGenerator;
public static byte[] encrypt(String txt, String key) throws Exception {
if (key == null) {
key = new String(defaultKey);
} else if (key.isEmpty()) {
key = getKey();
}
byte[] keyBytes = DatatypeConverter.parseBase64Binary(key);
byte[] txtBytes = txt.getBytes();
SecretKeySpec keySpc = new SecretKeySpec(keyBytes, ALGO);
cipher.init(Cipher.ENCRYPT_MODE, keySpc);
return cipher.doFinal(txtBytes);
}
private static String getKey() {
return getKeyInternal();
}
private static String getKeyInternal(){
return "xyzzzzzzzzzzzzzzzzzzzzzz";
}
public static String getKey(String src) {
String val = System.getProperty(src);
if (val == null) {
val = new String("defalultval");
}
return val;
}
public static void main(String[] args) {
String key = "testKey";
try {
cipher = Cipher.getInstance(ALGO_SPEC);
keyGenerator = KeyGenerator.getInstance(ALGO);
String keyStr = getKey(key);
if (keyStr == null) {
byte[] keyBytes = new byte[12];
keyBytes[0] = 0;
keyBytes[1] = 1;
defaultKey = new String(keyBytes);
} else {
defaultKey = keyStr;
}
byte[] encryption = encrypt("Hello World",keyStr);
} catch (Exception e) {
System.out.println("Issue happend");
}
System.out.println("Hello World");
}
}
| 1,835 | 23.157895 | 75 | java |
cryptoguard | cryptoguard-master/samples/VerySimple/very.java | import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class very {
public static void main(String[] args) throws Exception {
createURL("TestObject.git");
System.out.println("Hello World");
}
public static HttpURLConnection createURL(String tr) throws IOException {
URL url = new URL("http://publicobject.com/" + tr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
return connection;
}
}
| 541 | 26.1 | 81 | java |
cryptoguard | cryptoguard-master/samples/VerySimple_Gradle/src/main/java/very.java | import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class very {
public static void main(String[] args) throws Exception {
createURL("TestObject.git");
System.out.println("Hello World");
}
public static HttpURLConnection createURL(String tr) throws IOException {
URL url = new URL("http://publicobject.com/" + tr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
return connection;
}
}
| 541 | 26.1 | 81 | java |
cryptoguard | cryptoguard-master/samples/VerySimple_Gradle_Package/src/main/java/very.java | import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class very {
public static void main(String[] args) throws Exception {
createURL("TestObject.git");
System.out.println("Hello World");
}
public static HttpURLConnection createURL(String tr) throws IOException {
URL url = new URL("http://publicobject.com/" + tr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
return connection;
}
}
| 541 | 26.1 | 81 | java |
cryptoguard | cryptoguard-master/samples/VerySimple_NonVuln/very.java | import java.io.IOException;
public class very {
public static void main(String[] args) throws Exception {
System.out.println("Hello World");
}
}
| 149 | 20.428571 | 58 | java |
cryptoguard | cryptoguard-master/samples/gradle-nosub-master/src/main/java/org/rigorityj/main/BadAssymCrypto.java | package org.rigorityj.main;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class BadAssymCrypto {
public KeyPair generateKeyPairImplicit() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
return keyPairGenerator.genKeyPair();
}
public KeyPair generateKeyPairExplicit(int size) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(size, new SecureRandom());
return keyPairGenerator.genKeyPair();
}
}
| 714 | 27.6 | 86 | java |
cryptoguard | cryptoguard-master/samples/gradle-nosub-master/src/main/java/org/rigorityj/main/BadCertificateValidation.java | package org.rigorityj.main;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class BadCertificateValidation {
public SSLSocketFactory getSocketFactoryWithBadSelfsignedCertValidation() throws Exception {
TrustManager ignoreValidationTM = new X509TrustManager() {
private X509TrustManager trustManager;
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
if (x509CertificateArr == null || x509CertificateArr.length != 1) {
this.trustManager.checkServerTrusted(x509CertificateArr, str);
} else {
x509CertificateArr[0].checkValidity();
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{ignoreValidationTM}, new SecureRandom());
return sslContext.getSocketFactory();
}
public SSLSocketFactory getSocketFactoryWithTrustAllCertValidation() throws Exception {
TrustManager ignoreValidationTM = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Do Nothing
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
// Do nothing
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{ignoreValidationTM}, new SecureRandom());
return sslContext.getSocketFactory();
}
}
| 2,332 | 37.245902 | 122 | java |
cryptoguard | cryptoguard-master/samples/gradle-nosub-master/src/main/java/org/rigorityj/main/BadDigestAndRandom.java | package org.rigorityj.main;
import java.security.MessageDigest;
import java.util.Random;
public class BadDigestAndRandom {
public byte[] generateRandomBytes(long seed) {
byte[] randomBytes = new byte[64];
new Random(seed).nextBytes(randomBytes);
return randomBytes;
}
public static byte[] getDigest(String algo, String msg) throws Exception {
MessageDigest md = MessageDigest.getInstance(algo);
return md.digest(msg.getBytes());
}
}
| 495 | 22.619048 | 78 | java |
cryptoguard | cryptoguard-master/samples/gradle-nosub-master/src/main/java/org/rigorityj/main/BadHostnameVerification.java | package org.rigorityj.main;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import java.io.OutputStream;
import java.net.URL;
public class BadHostnameVerification {
public HttpsURLConnection connectWithBadHostnames() throws Exception {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
URL url = new URL("https://example.org/");
HttpsURLConnection urlConnection =
(HttpsURLConnection) url.openConnection();
urlConnection.setHostnameVerifier(hostnameVerifier);
return urlConnection;
}
public void writeToBadSocket() throws Exception {
SocketFactory sf = SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) sf.createSocket("gmail.com", 443);
OutputStream out = socket.getOutputStream();
out.write("Hello Bad guy! ;)".getBytes());
socket.close();
}
}
| 1,029 | 24.75 | 74 | java |
cryptoguard | cryptoguard-master/samples/gradle-nosub-master/src/main/java/org/rigorityj/main/BadSymCrypto.java | package org.rigorityj.main;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
/**
* Created by krishnokoli on 7/2/17.
*/
public class BadSymCrypto {
private String algo = "AES/CBC/PKCS5PADDING";
public BadSymCrypto(String algo) {
this.algo = algo;
}
public String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(algo);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
| 999 | 25.315789 | 93 | java |
cryptoguard | cryptoguard-master/samples/gradle-nosub-master/src/main/java/org/rigorityj/main/PasswordUtils.java | package org.rigorityj.main;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.Map;
/**
* Created by krishnokoli on 11/27/17.
*/
public class PasswordUtils {
private final String CRYPT_ALGO;
private String password;
private final char[] ENCRYPT_KEY;
private final byte[] SALT;
private final int ITERATION_COUNT;
private final char[] encryptKey;
private final byte[] salt;
private static final String LEN_SEPARATOR_STR = ":";
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static final String DEFAULT_ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV";
public static final String DEFAULT_SALT = "f77aLYLo";
public static final int DEFAULT_ITERATION_COUNT = 17;
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
private String encrypt() throws IOException {
String ret = null;
String strToEncrypt = null;
if (password == null) {
strToEncrypt = "";
} else {
strToEncrypt = password.length() + LEN_SEPARATOR_STR + password;
}
try {
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes());
ret = new String(DatatypeConverter.printBase64Binary(encryptedStr));
} catch (Throwable t) {
throw new IOException("Unable to encrypt password due to error", t);
}
return ret;
}
PasswordUtils(String aPassword) {
String[] crypt_algo_array = null;
int count = 0;
if (aPassword != null && aPassword.contains(",")) {
count = aPassword.split(",").length;
crypt_algo_array = aPassword.split(",");
}
if (crypt_algo_array != null && crypt_algo_array.length > 1) {
CRYPT_ALGO = crypt_algo_array[0];
ENCRYPT_KEY = crypt_algo_array[1].toCharArray();
SALT = crypt_algo_array[2].getBytes();
ITERATION_COUNT = Integer.parseInt(crypt_algo_array[3]);
password = crypt_algo_array[4];
if (count > 4) {
for (int i = 5; i <= count; i++) {
password = password + "," + crypt_algo_array[i];
}
}
} else {
CRYPT_ALGO = DEFAULT_CRYPT_ALGO;
ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
SALT = DEFAULT_SALT.getBytes();
ITERATION_COUNT = DEFAULT_ITERATION_COUNT;
password = aPassword;
}
Map<String, String> env = System.getenv();
String encryptKeyStr = env.get("ENCRYPT_KEY");
if (encryptKeyStr == null) {
encryptKey = ENCRYPT_KEY;
} else {
encryptKey = encryptKeyStr.toCharArray();
}
String saltStr = env.get("ENCRYPT_SALT");
if (saltStr == null) {
salt = SALT;
} else {
salt = saltStr.getBytes();
}
}
public static String decryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword)
.decrypt();
}
private String decrypt() throws IOException {
String ret = null;
try {
byte[] decodedPassword = DatatypeConverter.parseBase64Binary(password);
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
String decrypted = new String(engine.doFinal(decodedPassword));
int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR);
if (foundAt > -1) {
if (decrypted.length() > foundAt) {
ret = decrypted.substring(foundAt + 1);
} else {
ret = "";
}
} else {
ret = null;
}
} catch (Throwable t) {
throw new IOException("Unable to decrypt password due to error", t);
}
return ret;
}
}
| 4,823 | 36.107692 | 102 | java |
cryptoguard | cryptoguard-master/samples/gradle-nosub-master/src/main/java/org/rigorityj/main/VeryBadMain.java | package org.rigorityj.main;
import javax.xml.bind.DatatypeConverter;
import java.security.KeyPair;
public class VeryBadMain {
public static void main(String[] args) throws Exception {
BadAssymCrypto badCrypto = new BadAssymCrypto();
KeyPair kp = badCrypto.generateKeyPairExplicit(512);
System.out.println(kp.getPrivate().getEncoded());
BadDigestAndRandom badDigestAndRandom = new BadDigestAndRandom();
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("MD5", "Hello World!")));
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("SHA1", "Hello World!")));
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("SHA-512", "Hello World!")));
String key = "my+secret+key+lol";
String initVector = "RandomInitVector";
BadSymCrypto crypto = new BadSymCrypto("AES/CBC/PKCS5PADDING");
String decrypted = crypto.decrypt(key, initVector, "154asf15as4d5as4dasdfasf1sa5d");
System.out.println(decrypted);
String encrypted = PasswordUtils.encryptPassword("mypass,PBEWITHHMACSHA1ANDAES_128,my-sensitive-key,f77aLYLo,2000");
System.out.println(encrypted);
System.out.println(PasswordUtils.encryptPassword(encrypted));
}
}
| 1,334 | 39.454545 | 124 | java |
cryptoguard | cryptoguard-master/samples/gradle-sample-master/sample-main/src/main/java/org/rigorityj/BadCertificateValidation.java | package org.rigorityj;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class BadCertificateValidation {
public SSLSocketFactory getSocketFactoryWithBadSelfsignedCertValidation() throws Exception {
TrustManager ignoreValidationTM = new X509TrustManager() {
private X509TrustManager trustManager;
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
if (x509CertificateArr == null || x509CertificateArr.length != 1) {
this.trustManager.checkServerTrusted(x509CertificateArr, str);
} else {
x509CertificateArr[0].checkValidity();
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{ignoreValidationTM}, new SecureRandom());
return sslContext.getSocketFactory();
}
public SSLSocketFactory getSocketFactoryWithTrustAllCertValidation() throws Exception {
TrustManager ignoreValidationTM = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Do Nothing
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
// Do nothing
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{ignoreValidationTM}, new SecureRandom());
return sslContext.getSocketFactory();
}
}
| 2,327 | 37.163934 | 122 | java |
cryptoguard | cryptoguard-master/samples/gradle-sample-master/sample-main/src/main/java/org/rigorityj/BadHostnameVerification.java | package org.rigorityj;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import java.io.OutputStream;
import java.net.URL;
public class BadHostnameVerification {
public HttpsURLConnection connectWithBadHostnames() throws Exception {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
URL url = new URL("https://example.org/");
HttpsURLConnection urlConnection =
(HttpsURLConnection) url.openConnection();
urlConnection.setHostnameVerifier(hostnameVerifier);
return urlConnection;
}
public void writeToBadSocket() throws Exception {
SocketFactory sf = SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) sf.createSocket("gmail.com", 443);
OutputStream out = socket.getOutputStream();
out.write("Hello Bad guy! ;)".getBytes());
socket.close();
}
}
| 1,024 | 24.625 | 74 | java |
cryptoguard | cryptoguard-master/samples/gradle-sample-master/sample-main/src/main/java/org/rigorityj/VeryBadMain.java | package org.rigorityj;
import javax.xml.bind.DatatypeConverter;
import java.security.KeyPair;
public class VeryBadMain {
public static void main(String[] args) throws Exception {
BadAssymCrypto badCrypto = new BadAssymCrypto();
KeyPair kp = badCrypto.generateKeyPairExplicit(512);
System.out.println(kp.getPrivate().getEncoded());
BadDigestAndRandom badDigestAndRandom = new BadDigestAndRandom();
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("MD5", "Hello World!")));
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("SHA1", "Hello World!")));
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("SHA-512", "Hello World!")));
String key = "my+secret+key+lol";
String initVector = "RandomInitVector";
BadSymCrypto crypto = new BadSymCrypto("AES/CBC/PKCS5PADDING");
String decrypted = crypto.decrypt(key, initVector, "154asf15as4d5as4dasdfasf1sa5d");
System.out.println(decrypted);
String encrypted = PasswordUtils.encryptPassword("mypass,PBEWITHHMACSHA1ANDAES_128,my-sensitive-key,f77aLYLo,2000");
System.out.println(encrypted);
System.out.println(PasswordUtils.encryptPassword(encrypted));
}
}
| 1,329 | 39.30303 | 124 | java |
cryptoguard | cryptoguard-master/samples/gradle-sample-master/sample-util/src/main/java/org/rigorityj/BadAssymCrypto.java | package org.rigorityj;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class BadAssymCrypto {
public KeyPair generateKeyPairImplicit() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
return keyPairGenerator.genKeyPair();
}
public KeyPair generateKeyPairExplicit(int size) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(size, new SecureRandom());
return keyPairGenerator.genKeyPair();
}
}
| 709 | 27.4 | 86 | java |
cryptoguard | cryptoguard-master/samples/gradle-sample-master/sample-util/src/main/java/org/rigorityj/BadDigestAndRandom.java | package org.rigorityj;
import java.security.MessageDigest;
import java.util.Random;
public class BadDigestAndRandom {
public byte[] generateRandomBytes(long seed) {
byte[] randomBytes = new byte[64];
new Random(seed).nextBytes(randomBytes);
return randomBytes;
}
public static byte[] getDigest(String algo, String msg) throws Exception {
MessageDigest md = MessageDigest.getInstance(algo);
return md.digest(msg.getBytes());
}
}
| 490 | 22.380952 | 78 | java |
cryptoguard | cryptoguard-master/samples/gradle-sample-master/sample-util/src/main/java/org/rigorityj/BadSymCrypto.java | package org.rigorityj;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
/**
* Created by krishnokoli on 7/2/17.
*/
public class BadSymCrypto {
private String algo = "AES/CBC/PKCS5PADDING";
public BadSymCrypto(String algo) {
this.algo = algo;
}
public String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(algo);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
| 994 | 25.184211 | 93 | java |
cryptoguard | cryptoguard-master/samples/gradle-sample-master/sample-util/src/main/java/org/rigorityj/PasswordUtils.java | package org.rigorityj;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.Map;
/**
* Created by krishnokoli on 11/27/17.
*/
public class PasswordUtils {
private final String CRYPT_ALGO;
private String password;
private final char[] ENCRYPT_KEY;
private final byte[] SALT;
private final int ITERATION_COUNT;
private final char[] encryptKey;
private final byte[] salt;
private static final String LEN_SEPARATOR_STR = ":";
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static final String DEFAULT_ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV";
public static final String DEFAULT_SALT = "f77aLYLo";
public static final int DEFAULT_ITERATION_COUNT = 17;
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
private String encrypt() throws IOException {
String ret = null;
String strToEncrypt = null;
if (password == null) {
strToEncrypt = "";
} else {
strToEncrypt = password.length() + LEN_SEPARATOR_STR + password;
}
try {
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes());
ret = new String(DatatypeConverter.printBase64Binary(encryptedStr));
} catch (Throwable t) {
throw new IOException("Unable to encrypt password due to error", t);
}
return ret;
}
PasswordUtils(String aPassword) {
String[] crypt_algo_array = null;
int count = 0;
if (aPassword != null && aPassword.contains(",")) {
count = aPassword.split(",").length;
crypt_algo_array = aPassword.split(",");
}
if (crypt_algo_array != null && crypt_algo_array.length > 1) {
CRYPT_ALGO = crypt_algo_array[0];
ENCRYPT_KEY = crypt_algo_array[1].toCharArray();
SALT = crypt_algo_array[2].getBytes();
ITERATION_COUNT = Integer.parseInt(crypt_algo_array[3]);
password = crypt_algo_array[4];
if (count > 4) {
for (int i = 5; i <= count; i++) {
password = password + "," + crypt_algo_array[i];
}
}
} else {
CRYPT_ALGO = DEFAULT_CRYPT_ALGO;
ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
SALT = DEFAULT_SALT.getBytes();
ITERATION_COUNT = DEFAULT_ITERATION_COUNT;
password = aPassword;
}
Map<String, String> env = System.getenv();
String encryptKeyStr = env.get("ENCRYPT_KEY");
if (encryptKeyStr == null) {
encryptKey = ENCRYPT_KEY;
} else {
encryptKey = encryptKeyStr.toCharArray();
}
String saltStr = env.get("ENCRYPT_SALT");
if (saltStr == null) {
salt = SALT;
} else {
salt = saltStr.getBytes();
}
}
public static String decryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword)
.decrypt();
}
private String decrypt() throws IOException {
String ret = null;
try {
byte[] decodedPassword = DatatypeConverter.parseBase64Binary(password);
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
String decrypted = new String(engine.doFinal(decodedPassword));
int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR);
if (foundAt > -1) {
if (decrypted.length() > foundAt) {
ret = decrypted.substring(foundAt + 1);
} else {
ret = "";
}
} else {
ret = null;
}
} catch (Throwable t) {
throw new IOException("Unable to decrypt password due to error", t);
}
return ret;
}
}
| 4,818 | 36.069231 | 102 | java |
cryptoguard | cryptoguard-master/samples/mvn-sample-master/sample-main/src/main/java/org/rigorityj/BadCertificateValidation.java | package org.rigorityj;
import javax.net.ssl.*;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class BadCertificateValidation {
public SSLSocketFactory getSocketFactoryWithBadSelfsignedCertValidation() throws Exception {
TrustManager ignoreValidationTM = new X509TrustManager() {
private X509TrustManager trustManager;
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
if (x509CertificateArr == null || x509CertificateArr.length != 1) {
this.trustManager.checkServerTrusted(x509CertificateArr, str);
} else {
x509CertificateArr[0].checkValidity();
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{ignoreValidationTM}, new SecureRandom());
return sslContext.getSocketFactory();
}
public SSLSocketFactory getSocketFactoryWithTrustAllCertValidation() throws Exception {
TrustManager ignoreValidationTM = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Do Nothing
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
// Do nothing
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{ignoreValidationTM}, new SecureRandom());
return sslContext.getSocketFactory();
}
}
| 2,226 | 36.745763 | 122 | java |
cryptoguard | cryptoguard-master/samples/mvn-sample-master/sample-main/src/main/java/org/rigorityj/BadHostnameVerification.java | package org.rigorityj;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import java.io.OutputStream;
import java.net.URL;
public class BadHostnameVerification {
public HttpsURLConnection connectWithBadHostnames() throws Exception {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
URL url = new URL("https://example.org/");
HttpsURLConnection urlConnection =
(HttpsURLConnection) url.openConnection();
urlConnection.setHostnameVerifier(hostnameVerifier);
return urlConnection;
}
public void writeToBadSocket() throws Exception {
SocketFactory sf = SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) sf.createSocket("gmail.com", 443);
OutputStream out = socket.getOutputStream();
out.write("Hello Bad guy! ;)".getBytes());
socket.close();
}
}
| 1,024 | 24.625 | 74 | java |
cryptoguard | cryptoguard-master/samples/mvn-sample-master/sample-main/src/main/java/org/rigorityj/VeryBadMain.java | package org.rigorityj;
import javax.xml.bind.DatatypeConverter;
import java.security.KeyPair;
public class VeryBadMain {
public static void main(String[] args) throws Exception {
BadAssymCrypto badCrypto = new BadAssymCrypto();
KeyPair kp = badCrypto.generateKeyPairExplicit(512);
System.out.println(kp.getPrivate().getEncoded());
BadDigestAndRandom badDigestAndRandom = new BadDigestAndRandom();
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("MD5", "Hello World!")));
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("SHA1", "Hello World!")));
System.out.println(DatatypeConverter.printHexBinary(badDigestAndRandom.getDigest("SHA-512", "Hello World!")));
String key = "my+secret+key+lol";
String initVector = "RandomInitVector";
BadSymCrypto crypto = new BadSymCrypto("AES/CBC/PKCS5PADDING");
String decrypted = crypto.decrypt(key, initVector, "154asf15as4d5as4dasdfasf1sa5d");
System.out.println(decrypted);
String encrypted = PasswordUtils.encryptPassword("mypass,PBEWITHHMACSHA1ANDAES_128,my-sensitive-key,f77aLYLo,2000");
System.out.println(encrypted);
System.out.println(PasswordUtils.encryptPassword(encrypted));
}
}
| 1,329 | 39.30303 | 124 | java |
cryptoguard | cryptoguard-master/samples/mvn-sample-master/sample-util/src/main/java/org/rigorityj/BadAssymCrypto.java | package org.rigorityj;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class BadAssymCrypto {
public KeyPair generateKeyPairImplicit() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
return keyPairGenerator.genKeyPair();
}
public KeyPair generateKeyPairExplicit(int size) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(size, new SecureRandom());
return keyPairGenerator.genKeyPair();
}
}
| 709 | 27.4 | 86 | java |
cryptoguard | cryptoguard-master/samples/mvn-sample-master/sample-util/src/main/java/org/rigorityj/BadDigestAndRandom.java | package org.rigorityj;
import java.security.MessageDigest;
import java.util.Random;
public class BadDigestAndRandom {
public byte[] generateRandomBytes(long seed) {
byte[] randomBytes = new byte[64];
new Random(seed).nextBytes(randomBytes);
return randomBytes;
}
public static byte[] getDigest(String algo, String msg) throws Exception {
MessageDigest md = MessageDigest.getInstance(algo);
return md.digest(msg.getBytes());
}
}
| 490 | 22.380952 | 78 | java |
cryptoguard | cryptoguard-master/samples/mvn-sample-master/sample-util/src/main/java/org/rigorityj/BadSymCrypto.java | package org.rigorityj;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.*;
/**
* Created by krishnokoli on 7/2/17.
*/
public class BadSymCrypto {
private String algo = "AES/CBC/PKCS5PADDING";
public BadSymCrypto(String algo) {
this.algo = algo;
}
public String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(algo);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
| 1,018 | 25.128205 | 93 | java |
cryptoguard | cryptoguard-master/samples/mvn-sample-master/sample-util/src/main/java/org/rigorityj/PasswordUtils.java | package org.rigorityj;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.Map;
/**
* Created by krishnokoli on 11/27/17.
*/
public class PasswordUtils {
private final String CRYPT_ALGO;
private String password;
private final char[] ENCRYPT_KEY;
private final byte[] SALT;
private final int ITERATION_COUNT;
private final char[] encryptKey;
private final byte[] salt;
private static final String LEN_SEPARATOR_STR = ":";
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static final String DEFAULT_ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV";
public static final String DEFAULT_SALT = "f77aLYLo";
public static final int DEFAULT_ITERATION_COUNT = 17;
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
private String encrypt() throws IOException {
String ret = null;
String strToEncrypt = null;
if (password == null) {
strToEncrypt = "";
} else {
strToEncrypt = password.length() + LEN_SEPARATOR_STR + password;
}
try {
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes());
ret = new String(DatatypeConverter.printBase64Binary(encryptedStr));
} catch (Throwable t) {
throw new IOException("Unable to encrypt password due to error", t);
}
return ret;
}
PasswordUtils(String aPassword) {
String[] crypt_algo_array = null;
int count = 0;
if (aPassword != null && aPassword.contains(",")) {
count = aPassword.split(",").length;
crypt_algo_array = aPassword.split(",");
}
if (crypt_algo_array != null && crypt_algo_array.length > 1) {
CRYPT_ALGO = crypt_algo_array[0];
ENCRYPT_KEY = crypt_algo_array[1].toCharArray();
SALT = crypt_algo_array[2].getBytes();
ITERATION_COUNT = Integer.parseInt(crypt_algo_array[3]);
password = crypt_algo_array[4];
if (count > 4) {
for (int i = 5; i <= count; i++) {
password = password + "," + crypt_algo_array[i];
}
}
} else {
CRYPT_ALGO = DEFAULT_CRYPT_ALGO;
ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
SALT = DEFAULT_SALT.getBytes();
ITERATION_COUNT = DEFAULT_ITERATION_COUNT;
password = aPassword;
}
Map<String, String> env = System.getenv();
String encryptKeyStr = env.get("ENCRYPT_KEY");
if (encryptKeyStr == null) {
encryptKey = ENCRYPT_KEY;
} else {
encryptKey = encryptKeyStr.toCharArray();
}
String saltStr = env.get("ENCRYPT_SALT");
if (saltStr == null) {
salt = SALT;
} else {
salt = saltStr.getBytes();
}
}
public static String decryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword)
.decrypt();
}
private String decrypt() throws IOException {
String ret = null;
try {
byte[] decodedPassword = DatatypeConverter.parseBase64Binary(password);
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
String decrypted = new String(engine.doFinal(decodedPassword));
int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR);
if (foundAt > -1) {
if (decrypted.length() > foundAt) {
ret = decrypted.substring(foundAt + 1);
} else {
ret = "";
}
} else {
ret = null;
}
} catch (Throwable t) {
throw new IOException("Unable to decrypt password due to error", t);
}
return ret;
}
}
| 4,818 | 36.069231 | 102 | java |
cryptoguard | cryptoguard-master/samples/temp/tester/test.java | package tester;
public class test
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
} | 137 | 14.333333 | 42 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/Crypto.java | package tester;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Random;
/**
* Created by krishnokoli on 7/2/17.
*
* @author krishnokoli
* @since V01.00
*/
public class Crypto {
private String AES_ECB = "AES/ECB/PKCS5PADDING";
public Cipher cipher;
public void Crypto(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec1 = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher = Cipher.getInstance(AES_ECB);
long currentTime = System.nanoTime();
String currentTimeStr = String.valueOf(currentTime);
SecretKeySpec secretKeySpec = new SecretKeySpec(currentTimeStr.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
cipher.init(Cipher.DECRYPT_MODE, skeySpec1, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ DatatypeConverter.printBase64Binary(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public TrustManager getTrustManager() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
return defaultHostnameVerifier.verify("*.amap.com", sslSession);
}
};
HostnameVerifier hostnameVerifier1 = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
System.out.println(hostnameVerifier);
TrustManager ignoreValidationTM = new X509TrustManager() {
private X509TrustManager trustManager;
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
if (x509CertificateArr == null || x509CertificateArr.length != 1) {
this.trustManager.checkServerTrusted(x509CertificateArr, str);
} else {
x509CertificateArr[0].checkValidity();
}
}
};
return ignoreValidationTM;
}
public KeyPair generateKeyPair() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.setKeyEntry(null, null, "mypass".toCharArray(), null);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, new SecureRandom());
return keyPairGenerator.genKeyPair();
}
public KeyPair generateKeyPairDefaultKeySize() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.setKeyEntry(null, null, "mypass".toCharArray(), null);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
return keyPairGenerator.genKeyPair();
}
public void geCustomSocketFactory() throws IOException {
SocketFactory sf = SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) sf.createSocket("gmail.com", 443);
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSession s = socket.getSession();
// Verify that the certicate hostname is for mail.google.com
// This is due to lack of SNI support in the current SSLSocket.
if (!hv.verify("mail.google.com", s)) {
throw new SSLHandshakeException("Expected mail.google.com, not found " + s.getPeerPrincipal());
}
socket.close();
}
public byte[] randomNumberGeneration(long seed) {
byte[] randomBytes = new byte[64];
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(seed);
secureRandom.nextBytes(randomBytes);
return randomBytes;
}
public void main(String[] args) throws NoSuchAlgorithmException {
String key = "Bar12345Bar12345"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
MessageDigest md = MessageDigest.getInstance("SHA1");
MessageDigest md2 = MessageDigest.getInstance("SHA");
TrustManager trustManager = getTrustManager();
System.out.println(trustManager);
System.out.println(md.toString() + md2);
// decrypt(key, initVector, "abcd");
randomNumberGeneration(1000L);
//
while (args.length > 0) {
if (args[0].equals("g")) {
decrypt(key, initVector, "abcd");
}
}
}
}
| 6,192 | 32.475676 | 138 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/Crypto_VeryTemp.java | /**
*
*/
package tester;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Random;
/**
* Created by krishnokoli on 7/2/17.
*
* @author krishnokoli
* @since V01.00
*/
public class Crypto_VeryTemp {
private String AES_ECB = "AES/ECB/PKCS5PADDING";
public Cipher cipher;
public void Crypto(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec1 = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher = Cipher.getInstance(AES_ECB);
long currentTime = System.nanoTime();
String currentTimeStr = String.valueOf(currentTime);
SecretKeySpec secretKeySpec = new SecretKeySpec(currentTimeStr.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
cipher.init(Cipher.DECRYPT_MODE, skeySpec1, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ DatatypeConverter.printBase64Binary(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public TrustManager getTrustManager() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
return defaultHostnameVerifier.verify("*.amap.com", sslSession);
}
};
HostnameVerifier hostnameVerifier1 = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
System.out.println(hostnameVerifier);
TrustManager ignoreValidationTM = new X509TrustManager() {
private X509TrustManager trustManager;
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
if (x509CertificateArr == null || x509CertificateArr.length != 1) {
this.trustManager.checkServerTrusted(x509CertificateArr, str);
} else {
x509CertificateArr[0].checkValidity();
}
}
};
return ignoreValidationTM;
}
public KeyPair generateKeyPair() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.setKeyEntry(null, null, "mypass".toCharArray(), null);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, new SecureRandom());
return keyPairGenerator.genKeyPair();
}
public KeyPair generateKeyPairDefaultKeySize() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.setKeyEntry(null, null, "mypass".toCharArray(), null);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
return keyPairGenerator.genKeyPair();
}
public void geCustomSocketFactory() throws IOException {
SocketFactory sf = SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) sf.createSocket("gmail.com", 443);
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSession s = socket.getSession();
// Verify that the certicate hostname is for mail.google.com
// This is due to lack of SNI support in the current SSLSocket.
if (!hv.verify("mail.google.com", s)) {
throw new SSLHandshakeException("Expected mail.google.com, not found " + s.getPeerPrincipal());
}
socket.close();
}
public byte[] randomNumberGeneration(long seed) {
byte[] randomBytes = new byte[64];
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(seed);
secureRandom.nextBytes(randomBytes);
return randomBytes;
}
public void main(String[] args) throws NoSuchAlgorithmException {
String key = "Bar12345Bar12345"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
MessageDigest md = MessageDigest.getInstance("SHA1");
MessageDigest md2 = MessageDigest.getInstance("SHA");
TrustManager trustManager = getTrustManager();
System.out.println(trustManager);
System.out.println(md.toString() + md2);
// decrypt(key, initVector, "abcd");
randomNumberGeneration(1000L);
//
while (args.length > 0) {
if (args[0].equals("g")) {
decrypt(key, initVector, "abcd");
}
}
}
}
| 6,214 | 31.710526 | 138 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/LiveVarsClass.java | package tester;
public class LiveVarsClass {
private static String xxx1 = VeryBusyClass.xxx;
}
| 100 | 15.833333 | 51 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/NewTestCase1.java | package tester;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class NewTestCase1 {
public static void main(String[] args) throws UnsupportedEncodingException {
Map<String, String> hm = new HashMap<String, String>();
hm.put("aaa", "afix");
hm.put("bbb", "bfix");
hm.put("ccc", "cfix");
hm.put("ddd", "dfix");
String key = hm.get("aaa");
byte[] keyBytes = key.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
}
}
| 607 | 23.32 | 80 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/NewTestCase2.java | package tester;
import javax.crypto.spec.SecretKeySpec;
public class NewTestCase2 {
public static final String DEFAULT_ENCRYPT_KEY = "defaultkey";
private static char[] ENCRYPT_KEY;
private static char[] encryptKey;
public static void main(String[] args) {
go2();
go3();
go();
}
private static void go2() {
ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
}
private static void go3() {
encryptKey = ENCRYPT_KEY;
}
private static void go() {
byte[] keyBytes = encryptKey.toString().getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
}
}
| 664 | 21.166667 | 67 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/PBEUsage.java | package tester;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by krishnokoli on 11/15/17.
*
*
* @author krishnokoli
* @since V01.00
*/
public class PBEUsage {
private static final String MK_CIPHER = "AES";
private static final int MK_KeySize = 256;
private static final int SALT_SIZE = 8;
private static final String PBE_ALGO = "PBEWithMD5AndTripleDES";
private static final String MD_ALGO = "MD5";
private byte[] encryptMasterKey(String password) throws Throwable {
Key secretKey = generateMasterKey();
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey.getEncoded(), pbeKeySpec);
return masterKeyToDB;
}
private byte[] encryptMasterKey(String password, byte[] secretKey) throws Throwable {
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey, pbeKeySpec);
return masterKeyToDB;
}
private Key generateMasterKey() throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance(MK_CIPHER);
kg.init(MK_KeySize);
return kg.generateKey();
}
private PBEKeySpec getPBEParameterSpec(String password) throws Throwable {
MessageDigest md = MessageDigest.getInstance(MD_ALGO);
byte[] saltGen = md.digest(password.getBytes());
byte[] salt = new byte[SALT_SIZE];
System.arraycopy(saltGen, 0, salt, 0, SALT_SIZE);
int iteration = password.toCharArray().length + 1;
return new PBEKeySpec(password.toCharArray(), salt, iteration);
}
private byte[] encryptKey(byte[] data, PBEKeySpec keyspec) throws Throwable {
SecretKey key = getPasswordKey(keyspec);
if(keyspec.getSalt() != null) {
PBEParameterSpec paramSpec = new PBEParameterSpec(keyspec.getSalt(), keyspec.getIterationCount());
Cipher c = Cipher.getInstance(key.getAlgorithm());
c.init(Cipher.ENCRYPT_MODE, key,paramSpec);
return c.doFinal(data);
}
return null;
}
private SecretKey getPasswordKey(PBEKeySpec keyspec) throws Throwable {
SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGO);
return factory.generateSecret(keyspec);
}
}
| 2,590 | 35.492958 | 110 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/PassEncryptor.java | package tester;
public class PassEncryptor {
private SymCrypto symCrypto;
private String passKey = "pass.key";
private static final String prefix = "{key}";
public PassEncryptor() throws Exception {
symCrypto = new SymCrypto(passKey, prefix.length());
}
byte[] encPass(String pass, String src) throws Exception {
return symCrypto.encrypt(pass, "hardcoded");
}
}
| 411 | 21.888889 | 62 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/PasswordUtils.java | package tester;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.Map;
/**
* Created by krishnokoli on 11/27/17.
*
* @author krishnokoli
* @since V01.00
*/
public class PasswordUtils {
private final String CRYPT_ALGO;
private String password;
private final char[] ENCRYPT_KEY;
private final byte[] SALT;
private final int ITERATION_COUNT;
private final char[] encryptKey;
private final byte[] salt;
private static final String LEN_SEPARATOR_STR = ":";
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static final String DEFAULT_ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV";
public static final String DEFAULT_SALT = "f77aLYLo";
public static final int DEFAULT_ITERATION_COUNT = 17;
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
private String encrypt() throws IOException {
String ret = null;
String strToEncrypt = null;
if (password == null) {
strToEncrypt = "";
} else {
strToEncrypt = password.length() + LEN_SEPARATOR_STR + password;
}
try {
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes());
ret = new String(DatatypeConverter.printBase64Binary(encryptedStr));
} catch (Throwable t) {
throw new IOException("Unable to encrypt password due to error", t);
}
return ret;
}
PasswordUtils(String aPassword) {
String[] crypt_algo_array = null;
int count = 0;
if (aPassword != null && aPassword.contains(",")) {
count = aPassword.split(",").length;
crypt_algo_array = aPassword.split(",");
}
if (crypt_algo_array != null && crypt_algo_array.length > 1) {
CRYPT_ALGO = crypt_algo_array[0];
ENCRYPT_KEY = crypt_algo_array[1].toCharArray();
SALT = crypt_algo_array[2].getBytes();
ITERATION_COUNT = Integer.parseInt(crypt_algo_array[3]);
password = crypt_algo_array[4];
if (count > 4) {
for (int i = 5; i <= count; i++) {
password = password + "," + crypt_algo_array[i];
}
}
} else {
CRYPT_ALGO = DEFAULT_CRYPT_ALGO;
ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
SALT = DEFAULT_SALT.getBytes();
ITERATION_COUNT = DEFAULT_ITERATION_COUNT;
password = aPassword;
}
Map<String, String> env = System.getenv();
String encryptKeyStr = env.get("ENCRYPT_KEY");
if (encryptKeyStr == null) {
encryptKey = ENCRYPT_KEY;
} else {
encryptKey = encryptKeyStr.toCharArray();
}
String saltStr = env.get("ENCRYPT_SALT");
if (saltStr == null) {
salt = SALT;
} else {
salt = saltStr.getBytes();
}
}
public static String decryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword)
.decrypt();
}
private String decrypt() throws IOException {
String ret = null;
try {
byte[] decodedPassword = DatatypeConverter.parseBase64Binary(password);
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
String decrypted = new String(engine.doFinal(decodedPassword));
int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR);
if (foundAt > -1) {
if (decrypted.length() > foundAt) {
ret = decrypted.substring(foundAt + 1);
} else {
ret = "";
}
} else {
ret = null;
}
} catch (Throwable t) {
throw new IOException("Unable to decrypt password due to error", t);
}
return ret;
}
}
| 4,854 | 35.503759 | 102 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/SymCrypto.java | package tester;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class SymCrypto {
private String ALGO = "AES";
private String ALGO_SPEC = "AES/CBC/NoPadding";
private String defaultKey;
private Cipher cipher;
private KeyGenerator keyGenerator;
public SymCrypto(String key, int size) throws Exception {
cipher = Cipher.getInstance(ALGO_SPEC);
keyGenerator = KeyGenerator.getInstance(ALGO);
String keyStr = getKey(key);
if (keyStr == null) {
byte[] keyBytes = new byte[12];
keyBytes[0] = 0;
keyBytes[1] = 1;
defaultKey = new String(keyBytes);
} else {
defaultKey = keyStr;
}
}
public byte[] encrypt(String txt, String key) throws Exception {
if (key == null) {
key = new String(defaultKey);
} else if (key.isEmpty()) {
key = getKey();
}
byte[] keyBytes = DatatypeConverter.parseBase64Binary(key);
byte[] txtBytes = txt.getBytes();
SecretKeySpec keySpc = new SecretKeySpec(keyBytes, ALGO);
cipher.init(Cipher.ENCRYPT_MODE, keySpc);
return cipher.doFinal(txtBytes);
}
private String getKey() {
return getKeyInternal();
}
private String getKeyInternal(){
return "xyzzzzzzzzzzzzzzzzzzzzzz";
}
public String getKey(String src) {
String val = System.getProperty(src);
if (val == null) {
val = new String("defalultval");
}
return val;
}
}
| 1,664 | 23.850746 | 68 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/UrlFrameWorks.java | package tester;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlFrameWorks {
private static String apiBaseUrl = "http://abc.com";
private static Retrofit.Builder builder =
new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(apiBaseUrl);
public HttpURLConnection createURL(String tr) throws IOException {
URL url = new URL("http://publicobject.com/helloworld.txt");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
return connection;
}
private Request createUrlUsingOkHttp1(String tr) {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
return request;
}
private void createUrlUsingOkHttp2() {
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://ajax.googleapis.com/ajax/services/search/images").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("q", "android");
urlBuilder.addQueryParameter("rsz", "8");
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
}
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
public static void changeApiBaseUrl(String newApiBaseUrl) {
apiBaseUrl = newApiBaseUrl;
builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(apiBaseUrl);
}
}
| 1,904 | 28.765625 | 123 | java |
cryptoguard | cryptoguard-master/samples/testable-jar/src/main/java/tester/VeryBusyClass.java |
package tester;
import java.io.IOException;
public class VeryBusyClass
{
public static final String xxx = "aaaaaaa";
public void main(String[] args) throws IOException {
PasswordUtils.decryptPassword("helloworld");
}
}
| 228 | 15.357143 | 53 | java |
cryptoguard | cryptoguard-master/src/main/java/CWE_Reader/CWE.java | /* Licensed under GPL-3.0 */
package CWE_Reader;
/**
* CWE class.
*
* @author CryptoguardTeam Created on 2018-12-05.
* @version 03.07.01
* @since 01.00.07
* <p>The Class containing the CWE Info
*/
public class CWE {
//region Attributes
private Integer id;
private String name;
private String weaknessAbstraction;
private String description;
private String extendedDescription;
//endregion
/**
* The cwe general info body This class only carries a brief subset of the full information of a
* CWE
*
* @param id {@link java.lang.Integer} - The id of the CWE
* @param name {@link java.lang.String} - The name of the CWE
* @param weaknessAbstraction {@link java.lang.String} - The weakness type of the CWE
* @param description {@link java.lang.String} - The short description of the CWE
* @param extendedDescription {@link java.lang.String} - The extended description of the CWE
*/
public CWE(
Integer id,
String name,
String weaknessAbstraction,
String description,
String extendedDescription) {
this.id = id;
this.name = name;
this.weaknessAbstraction = weaknessAbstraction;
this.description = description;
this.extendedDescription = extendedDescription;
}
//region Getters
/**
* Getter for id
*
* <p>getId()
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getId() {
return id;
}
/**
* Getter for name
*
* <p>getName()
*
* @return a {@link java.lang.String} object.
*/
public String getName() {
return name;
}
/**
* Getter for weaknessAbstraction
*
* <p>getWeaknessAbstraction()
*
* @return a {@link java.lang.String} object.
*/
public String getWeaknessAbstraction() {
return weaknessAbstraction;
}
/**
* Getter for description
*
* <p>getDescription()
*
* @return a {@link java.lang.String} object.
*/
public String getDescription() {
return description;
}
/**
* Getter for extendedDescription
*
* <p>getExtendedDescription()
*
* @return a {@link java.lang.String} object.
*/
public String getExtendedDescription() {
return extendedDescription;
}
//endregion
}
| 2,238 | 20.737864 | 98 | java |
cryptoguard | cryptoguard-master/src/main/java/CWE_Reader/CWEList.java | /* Licensed under GPL-3.0 */
package CWE_Reader;
import java.util.HashMap;
import java.util.Map;
/**
* CWEList class.
*
* @author CryptoguardTeam Created on 2018-12-05.
* @version 03.07.01
* @since 01.00.07
* <p>The Lazy CWE Loader that retrieves CWES for Java
*/
public class CWEList {
//region Attributes
private final Double cweVersion = 3.1;
private Map<Integer, CWE> cweList;
//endregion
/** The empty constructor for this class */
public CWEList() {}
//region Getters
/**
* The "Lazy Loading" Getter for cweList
*
* <p>getCweList()
*
* @return a {@link java.util.Map} object.
*/
public Map<Integer, CWE> getCweList() {
if (this.cweList == null) CWE_Loader();
return cweList;
}
/**
* The "Lazy Loading" for CWE
*
* <p>CWE_Loader()
*/
private void CWE_Loader() {
this.cweList = new HashMap<>();
this.cweList.put(
256,
new CWE(
256,
"Unprotected Storage of Credentials",
"Variant,Incomplete",
"Storing a password in plaintext may result in a system compromise.",
"Password management issues occur when a password is stored in plaintext in an application's properties or configuration file. Storing a plaintext password in a configuration file allows anyone who can read the file access to the password-protected resource.\n::NATURE:ChildOf:CWE ID:522:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:522:VIEW ID:699:ORDINAL:Primary::NATURE:CanAlsoBe:CWE ID:319:VIEW ID:1000::NATURE:CanAlsoBe:CWE ID:319:VIEW ID:699::\n::ORDINALITY:Primary:DESCRIPTION:::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Architecture and Design:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Gain Privileges or Assume Identity::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Avoid storing passwords in easily accessible locations.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Consider storing cryptographic hashes of passwords as an alternative to storing in plaintext.::PHASE::STRATEGY::EFFECTIVENESS:None:DESCRIPTION:A programmer might attempt to remedy the password management problem by obscuring the password with an encoding function, such as base 64 encoding, but this effort does not adequately protect the password because the encoding can be detected and decoded easily.::\nTAXONOMY NAME:7 Pernicious Kingdoms:ENTRY NAME:Password Management::::TAXONOMY NAME:Software Fault Patterns:ENTRY ID:SFP23:ENTRY NAME:Exposed Data::"));
this.cweList.put(
759,
new CWE(
759,
"Use of a One-Way Hash without a Salt",
"Base ",
"Incomplete",
"The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software does not also use a salt as part of the input.\nThis makes it easier for attackers to pre-compute the hash value using dictionary attack techniques such as rainbow tables. It should be noted that, despite common perceptions, the use of a good salt with a hash does not sufficiently increase the effort for an attacker who is targeting an individual password, or who has a large amount of computing resources available, such as with cloud-based services or specialized, inexpensive hardware. Offline password cracking can still be effective if the hash function is not expensive to compute; many cryptographic functions are designed to be efficient and can be vulnerable to attacks using massive computing resources, even if the hash is cryptographically strong. The use of a salt only slightly increases the computing requirements for an attacker compared to other strategies such as adaptive hash functions. See CWE-916 for more details.\n::NATURE:ChildOf:CWE ID:916:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:916:VIEW ID:1000:ORDINAL:Primary::\n::In cryptography, salt refers to some random addition of data to an input before hashing to make dictionary attacks more difficult.::\n:::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity:NOTE:Access Control Bypass Protection Mechanism Gain Privileges or Assume Identity If an attacker can gain access to the hashes, then the lack of a salt makes it easier to conduct brute force attacks using techniques such as rainbow tables.::\n::METHOD:Automated Static Analysis - Binary or Bytecode:EFFECTIVENESS:SOAR Partial:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Bytecode Weakness Analysis - including disassembler + source code weakness analysis Binary Weakness Analysis - including disassembler + source code weakness analysis::METHOD:Manual Static Analysis - Binary or Bytecode:EFFECTIVENESS:SOAR Partial:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies::METHOD:Manual Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Focused Manual Spotcheck - Focused manual analysis of source Manual Source Code Review (not inspections)::METHOD:Automated Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Source code Weakness Analyzer Context-configured Source Code Weakness Analyzer::METHOD:Automated Static Analysis:EFFECTIVENESS:SOAR Partial:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Cost effective for partial coverage: Configuration Checker::METHOD:Architecture or Design Review:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Formal Methods / Correct-By-Construction Cost effective for partial coverage: Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS:High:DESCRIPTION:Use an adaptive hash function that can be configured to change the amount of computational effort needed to compute the hash, such as the number of iterations (stretching) or the amount of memory required. Some hash functions perform salting automatically. These functions can significantly increase the overhead for a brute force attack compared to intentionally-fast functions such as MD5. For example, rainbow table attacks can become infeasible due to the high computing overhead. Finally, since computing power gets faster and cheaper over time, the technique can be reconfigured to increase the workload without forcing an entire replacement of the algorithm in use. Some hash functions that have one or more of these desired properties include bcrypt [REF-291], scrypt [REF-292], and PBKDF2 [REF-293]. While there is active debate about which of these is the most effective, they are all stronger than using salts with hash functions with very little computing overhead. Note that using these functions can have an impact on performance, so they require special consideration to avoid denial-of-service attacks. However, their configurability provides finer control over how much CPU and memory is used, so it could be adjusted to suit the environment's needs.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS:Limited:DESCRIPTION:If a technique that requires extra computational effort can not be implemented, then for each password that is processed, generate a new random salt using a strong random number generator with unpredictable seeds. Add the salt to the plaintext password before hashing it. When storing the hash, also store the salt. Do not use the same salt for every password.::PHASE:Implementation Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:When using industry-approved techniques, use them correctly. Don't cut corners by skipping resource-intensive steps (CWE-325). These steps are often essential for preventing common attacks.::\n::REFERENCE:CVE-2008-1526:DESCRIPTION:Router does not use a salt with a hash, making it easier to crack passwords.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-1526REFERENCE:CVE-2006-1058:DESCRIPTION:Router does not use a salt with a hash, making it easier to crack passwords.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1058\n"));
this.cweList.put(
547,
new CWE(
547,
"Use of Hard-coded, Security-relevant Constants",
"Variant",
"Draft",
"The program uses hard-coded constants instead of symbolic names for security-critical values, which increases the likelihood of mistakes during code maintenance or security policy change.\nIf the developer does not find all occurrences of the hard-coded constants, an incorrect policy decision may be made if one of the constants is not changed. Making changes to these values will require code changes that may be difficult or impossible once the system is released to the field. In addition, these hard-coded values may become available to attackers if the code is ever disclosed.\n::NATURE:ChildOf:CWE ID:710:VIEW ID:1000:ORDINAL:Primary::\n:::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Other:TECHNICAL IMPACT:Varies by Context Quality Degradation:NOTE:Other Varies by Context Quality Degradation The existence of hardcoded constants could cause unexpected behavior and the introduction of weaknesses during code maintenance or when making changes to the code if all occurrences are not modified. The use of hardcoded constants is an indication of poor quality.::\n::PHASE:Implementation:STRATEGY::EFFECTIVENESS::DESCRIPTION:Avoid using hard-coded constants. Configuration files offer a more flexible solution.::\nTAXONOMY NAME:CERT C Secure Coding:ENTRY ID:DCL06-C:ENTRY NAME:Use meaningful symbolic constants to represent literal values in program logic::"));
this.cweList.put(
349,
new CWE(
349,
"Acceptance of Extraneous Untrusted Data With Trusted Data",
"Base",
"Draft",
"The software, when processing trusted data, accepts any untrusted data that is also included with the trusted data, treating the untrusted data as if it were trusted.\n::NATURE:ChildOf:CWE ID:345:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:345:VIEW ID:699:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:SCOPE:Integrity:TECHNICAL IMPACT:Bypass Protection Mechanism Modify Application Data:NOTE:Access Control Integrity Bypass Protection Mechanism Modify Application Data An attacker could package untrusted data with trusted data to bypass protection mechanisms to gain access to and possibly modify sensitive data.::\n::REFERENCE:CVE-2002-0018:DESCRIPTION:Does not verify that trusted entity is authoritative for all entities in its response.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-0018\nTAXONOMY NAME:PLOVER:ENTRY NAME:Untrusted Data Appended with Trusted Data::::TAXONOMY NAME:CERT Java Secure Coding:ENTRY ID:ENV01-J:ENTRY NAME:Place all security-sensitive code in a single JAR and sign and seal it::\n::141::142::75::"));
this.cweList.put(
321,
new CWE(
321,
"Use of Hard-coded Cryptographic Key",
"Base",
"Draft",
"The use of a hard-coded cryptographic key significantly increases the possibility that encrypted data may be recovered.\n::NATURE:ChildOf:CWE ID:798:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:798:VIEW ID:699:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity:NOTE:Access Control Bypass Protection Mechanism Gain Privileges or Assume Identity If hard-coded cryptographic keys are used, it is almost certain that malicious users will gain access through the account in question.::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Prevention schemes mirror that of hard-coded password storage.::\nTAXONOMY NAME:CLASP:ENTRY NAME:Use of hard-coded cryptographic key::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A8:ENTRY NAME:Insecure Cryptographic Storage:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A9:ENTRY NAME:Insecure Communications:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2004:ENTRY ID:A8:ENTRY NAME:Insecure Storage:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:Software Fault Patterns:ENTRY ID:SFP33:ENTRY NAME:Hardcoded sensitive data::\nTYPE:Other:NOTE:The main difference between the use of hard-coded passwords and the use of hard-coded cryptographic keys is the false sense of security that the former conveys. Many people believe that simply hashing a hard-coded password before storage will protect the information from malicious users. However, many hashes are reversible (or at least vulnerable to brute force attacks) -- and further, many authentication protocols simply request the hash itself, making it no better than a password.::"));
this.cweList.put(
601,
new CWE(
601,
"URL Redirection to Untrusted Site ('Open Redirect')",
"Variant",
"Draft",
"A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.\nAn http parameter may contain a URL value and could cause the web application to redirect the request to the specified URL. By modifying the URL value to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site, phishing attempts have a more trustworthy appearance.\n::NATURE:ChildOf:CWE ID:610:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:20:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:20:VIEW ID:1003:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::PARADIGN NAME:Web Based:PARADIGN PREVALENCE:Undetermined::\n::Phishing is a general term for deceptive attempts to coerce private information from users that will be used for identity theft.::\n::TERM:Open Redirect:DESCRIPTION:::TERM:Cross-site Redirect:DESCRIPTION:::TERM:Cross-domain Redirect:DESCRIPTION:::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity:NOTE:Access Control Bypass Protection Mechanism Gain Privileges or Assume Identity The user may be redirected to an untrusted page that contains malware which may then compromise the user's machine. This will expose the user to extensive risk and the user's interaction with the web server may also be compromised if the malware conducts keylogging or other attacks that steal credentials, personally identifiable information (PII), or other important data.::SCOPE:Access Control:SCOPE:Confidentiality:SCOPE:Other:TECHNICAL IMPACT:Bypass Protection Mechanism Gain Privileges or Assume Identity Other:NOTE:Access Control Confidentiality Other Bypass Protection Mechanism Gain Privileges or Assume Identity Other The user may be subjected to phishing attacks by being redirected to an untrusted page. The phishing attack may point to an attacker controlled web page that appears to be a trusted web site. The phishers may then steal the user's credentials and then use these credentials to access the legitimate web site.::\n::METHOD:Manual Static Analysis:EFFECTIVENESS:High:DESCRIPTION:Since this weakness does not typically appear frequently within a single software package, manual white box techniques may be able to provide sufficient code coverage and reduction of false positives if all potentially-vulnerable operations can be assessed within limited time constraints.::METHOD:Automated Dynamic Analysis:EFFECTIVENESS::DESCRIPTION:Automated black box tools that supply URLs to every input may be able to spot Location header modifications, but test case coverage is a factor, and custom redirects may not be detected.::METHOD:Automated Static Analysis:EFFECTIVENESS::DESCRIPTION:Automated static analysis tools may not be able to determine whether input influences the beginning of a URL, which is important for reducing false positives.::METHOD:Other:EFFECTIVENESS::DESCRIPTION:Whether this issue poses a vulnerability will be subject to the intended behavior of the application. For example, a search engine might intentionally provide redirects to arbitrary URLs.::METHOD:Automated Static Analysis - Binary or Bytecode:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Bytecode Weakness Analysis - including disassembler + source code weakness analysis Binary Weakness Analysis - including disassembler + source code weakness analysis::METHOD:Dynamic Analysis with Automated Results Interpretation:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Web Application Scanner Web Services Scanner Database Scanners::METHOD:Dynamic Analysis with Manual Results Interpretation:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Fuzz Tester Framework-based Fuzzer::METHOD:Manual Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Manual Source Code Review (not inspections)::METHOD:Automated Static Analysis - Source Code:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Source code Weakness Analyzer Context-configured Source Code Weakness Analyzer::METHOD:Architecture or Design Review:EFFECTIVENESS:High:DESCRIPTION:According to SOAR, the following detection techniques may be useful: Highly cost effective: Formal Methods / Correct-By-Construction Cost effective for partial coverage: Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)::\n::PHASE:Implementation:STRATEGY:Input Validation:EFFECTIVENESS::DESCRIPTION:Assume all input is malicious. Use an accept known good input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, boat may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as red or blue. Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Use a whitelist of approved URLs or domains to be used for redirection.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Use an intermediate disclaimer page that provides the user with a clear warning that they are leaving the current site. Implement a long timeout before the redirect occurs, or force the user to click on the link. Be careful to avoid XSS problems (CWE-79) when generating the disclaimer page.::PHASE:Architecture and Design:STRATEGY:Enforcement by Conversion:EFFECTIVENESS::DESCRIPTION:When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs. For example, ID 1 could map to /login.asp and ID 2 could map to http://www.example.com/. Features such as the ESAPI AccessReferenceMap [REF-45] provide this capability.::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Ensure that no externally-supplied requests are honored by requiring that all redirect requests include a unique nonce generated by the application [REF-483]. Be sure that the nonce is not predictable (CWE-330).::PHASE:Architecture and Design Implementation:STRATEGY:Attack Surface Reduction:EFFECTIVENESS::DESCRIPTION:Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Many open redirect problems occur because the programmer assumed that certain inputs could not be modified, such as cookies and hidden form fields.::PHASE:Operation:STRATEGY:Firewall:EFFECTIVENESS:Moderate:DESCRIPTION:Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth.::\n::REFERENCE:CVE-2005-4206:DESCRIPTION:URL parameter loads the URL into a frame and causes it to appear to be part of a valid page.:LINK:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-4206REFERENCE:CVE-2008-2951:DESCRIPTION:An open redirect vulnerability in the search script in the software allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via a URL as a parameter to the proper function.:LINK:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2951REFERENCE:CVE-2008-2052:DESCRIPTION:Open redirect vulnerability in the software allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via a URL in the proper parameter.:LINK:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2052\nTAXONOMY NAME:WASC:ENTRY ID:38:ENTRY NAME:URl Redirector Abuse::::TAXONOMY NAME:Software Fault Patterns:ENTRY ID:SFP24:ENTRY NAME:Tainted input to command::\n::194::"));
this.cweList.put(
650,
new CWE(
650,
"Trusting HTTP Permission Methods on the Server Side",
"Variant",
"Incomplete",
"The server contains a protection mechanism that assumes that any URI that is accessed using HTTP GET will not cause a state change to the associated resource. This might allow attackers to bypass intended access restrictions and conduct resource modification and deletion attacks, since some applications allow GET to modify state.\nThe HTTP GET method and some other methods are designed to retrieve resources and not to alter the state of the application or resources on the server side. Furthermore, the HTTP specification requires that GET requests (and other requests) should not have side effects. Believing that it will be enough to prevent unintended resource alterations, an application may disallow the HTTP requests to perform DELETE, PUT and POST operations on the resource representation. However, there is nothing in the HTTP protocol itself that actually prevents the HTTP GET method from performing more than just query of the data. Developers can easily code programs that accept a HTTP GET request that do in fact create, update or delete data on the server. For instance, it is a common practice with REST based Web Services to have HTTP GET requests modifying resources on the server side. However, whenever that happens, the access control needs to be properly enforced in the application. No assumptions should be made that only HTTP DELETE, PUT, POST, and other methods have the power to alter the representation of the resource being accessed in the request.\n::NATURE:ChildOf:CWE ID:436:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:436:VIEW ID:699:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION::::PHASE:Operation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Gain Privileges or Assume Identity:NOTE:Access Control Gain Privileges or Assume Identity An attacker could escalate privileges.::SCOPE:Integrity:TECHNICAL IMPACT:Modify Application Data:NOTE:Integrity Modify Application Data An attacker could modify resources.::SCOPE:Confidentiality:TECHNICAL IMPACT:Read Application Data:NOTE:Confidentiality Read Application Data An attacker could obtain sensitive information.::\n::PHASE:System Configuration:STRATEGY::EFFECTIVENESS::DESCRIPTION:Configure ACLs on the server side to ensure that proper level of access control is defined for each accessible resource representation.::\n"));
this.cweList.put(
326,
new CWE(
326,
"Inadequate Encryption Strength",
"Class",
"Draft",
"The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.\nA weak encryption scheme can be subjected to brute force attacks that have a reasonable chance of succeeding using current attack methods and resources.\n::NATURE:ChildOf:CWE ID:693:VIEW ID:1000:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION:::\n::SCOPE:Access Control:SCOPE:Confidentiality:TECHNICAL IMPACT:Bypass Protection Mechanism Read Application Data:NOTE:Access Control Confidentiality Bypass Protection Mechanism Read Application Data An attacker may be able to decrypt the data using brute force attacks.::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Use a cryptographic algorithm that is currently considered to be strong by experts in the field.::\n::REFERENCE:CVE-2001-1546:DESCRIPTION:Weak encryption:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2001-1546REFERENCE:CVE-2004-2172:DESCRIPTION:Weak encryption (chosen plaintext attack):LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2004-2172REFERENCE:CVE-2002-1682:DESCRIPTION:Weak encryption:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1682REFERENCE:CVE-2002-1697:DESCRIPTION:Weak encryption produces same ciphertext from the same plaintext blocks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1697REFERENCE:CVE-2002-1739:DESCRIPTION:Weak encryption:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1739REFERENCE:CVE-2005-2281:DESCRIPTION:Weak encryption scheme:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-2281REFERENCE:CVE-2002-1872:DESCRIPTION:Weak encryption (XOR):LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1872REFERENCE:CVE-2002-1910:DESCRIPTION:Weak encryption (reversible algorithm).:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1910REFERENCE:CVE-2002-1946:DESCRIPTION:Weak encryption (one-to-one mapping).:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1946REFERENCE:CVE-2002-1975:DESCRIPTION:Encryption error uses fixed salt, simplifying brute force / dictionary attacks (overlaps randomness).:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1975\nTAXONOMY NAME:PLOVER:ENTRY NAME:Weak Encryption::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A8:ENTRY NAME:Insecure Cryptographic Storage:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2007:ENTRY ID:A9:ENTRY NAME:Insecure Communications:MAPPING FIT:CWE More Specific::::TAXONOMY NAME:OWASP Top Ten 2004:ENTRY ID:A8:ENTRY NAME:Insecure Storage:MAPPING FIT:CWE More Specific::\n::112::20::\nTYPE:Maintenance:NOTE:A variety of encryption algorithms exist, with various weaknesses. This category could probably be split into smaller sub-categories.::::TYPE:Maintenance:NOTE:Relationships between CWE-310, CWE-326, and CWE-327 and all their children need to be reviewed and reorganized.::"));
this.cweList.put(
760,
new CWE(
760,
"Use of a One-Way Hash with a Predictable Salt",
"Base",
"Incomplete",
"The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software uses a predictable salt as part of the input.\nThis makes it easier for attackers to pre-compute the hash value using dictionary attack techniques such as rainbow tables, effectively disabling the protection that an unpredictable salt would provide. It should be noted that, despite common perceptions, the use of a good salt with a hash does not sufficiently increase the effort for an attacker who is targeting an individual password, or who has a large amount of computing resources available, such as with cloud-based services or specialized, inexpensive hardware. Offline password cracking can still be effective if the hash function is not expensive to compute; many cryptographic functions are designed to be efficient and can be vulnerable to attacks using massive computing resources, even if the hash is cryptographically strong. The use of a salt only slightly increases the computing requirements for an attacker compared to other strategies such as adaptive hash functions. See CWE-916 for more details.\n::NATURE:ChildOf:CWE ID:916:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:916:VIEW ID:1000:ORDINAL:Primary::\n::In cryptography, salt refers to some random addition of data to an input before hashing to make dictionary attacks more difficult.::\n:::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS:High:DESCRIPTION:Use an adaptive hash function that can be configured to change the amount of computational effort needed to compute the hash, such as the number of iterations (stretching) or the amount of memory required. Some hash functions perform salting automatically. These functions can significantly increase the overhead for a brute force attack compared to intentionally-fast functions such as MD5. For example, rainbow table attacks can become infeasible due to the high computing overhead. Finally, since computing power gets faster and cheaper over time, the technique can be reconfigured to increase the workload without forcing an entire replacement of the algorithm in use. Some hash functions that have one or more of these desired properties include bcrypt [REF-291], scrypt [REF-292], and PBKDF2 [REF-293]. While there is active debate about which of these is the most effective, they are all stronger than using salts with hash functions with very little computing overhead. Note that using these functions can have an impact on performance, so they require special consideration to avoid denial-of-service attacks. However, their configurability provides finer control over how much CPU and memory is used, so it could be adjusted to suit the environment's needs.::PHASE:Implementation:STRATEGY::EFFECTIVENESS:Limited:DESCRIPTION:If a technique that requires extra computational effort can not be implemented, then for each password that is processed, generate a new random salt using a strong random number generator with unpredictable seeds. Add the salt to the plaintext password before hashing it. When storing the hash, also store the salt. Do not use the same salt for every password.::\n::REFERENCE:CVE-2008-4905:DESCRIPTION:Blogging software uses a hard-coded salt when calculating a password hash.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-4905REFERENCE:CVE-2002-1657:DESCRIPTION:Database server uses the username for a salt when encrypting passwords, simplifying brute force attacks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1657REFERENCE:CVE-2001-0967:DESCRIPTION:Server uses a constant salt when encrypting passwords, simplifying brute force attacks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2001-0967REFERENCE:CVE-2005-0408:DESCRIPTION:chain: product generates predictable MD5 hashes using a constant value combined with username, allowing authentication bypass.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-0408"));
this.cweList.put(
338,
new CWE(
338,
"Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)",
"Base",
"Draft",
"The product uses a Pseudo-Random Number Generator (PRNG) in a security context, but the PRNG's algorithm is not cryptographically strong.\nWhen a non-cryptographic PRNG is used in a cryptographic context, it can expose the cryptography to certain types of attacks. Often a pseudo-random number generator (PRNG) is not designed for cryptography. Sometimes a mediocre source of randomness is sufficient or preferable for algorithms that use random numbers. Weak generators generally take less processing power and/or do not use the precious, finite, entropy sources on a system. While such PRNGs might have very useful features, these same features could be used to break the cryptography.\n::NATURE:ChildOf:CWE ID:330:VIEW ID:1000:ORDINAL:Primary::NATURE:ChildOf:CWE ID:330:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:330:VIEW ID:1003:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Bypass Protection Mechanism:NOTE:Access Control Bypass Protection Mechanism If a PRNG is used for authentication and authorization, such as a session ID or a seed for generating a cryptographic key, then an attacker may be able to easily guess the ID or cryptographic key and gain access to restricted functionality.::\n::PHASE:Implementation:STRATEGY::EFFECTIVENESS::DESCRIPTION:Use functions or hardware which use a hardware-based random number generation for all crypto. This is the recommended solution. Use CyptGenRandom on Windows, or hw_rand() on Linux.::\n::REFERENCE:CVE-2009-3278:DESCRIPTION:Crypto product uses rand() library function to generate a recovery key, making it easier to conduct brute force attacks.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3278REFERENCE:CVE-2009-3238:DESCRIPTION:Random number generator can repeatedly generate the same value.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3238REFERENCE:CVE-2009-2367:DESCRIPTION:Web application generates predictable session IDs, allowing session hijacking.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-2367REFERENCE:CVE-2008-0166:DESCRIPTION:SSL library uses a weak random number generator that only generates 65,536 unique keys.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-0166\nTAXONOMY NAME:CLASP:ENTRY NAME:Non-cryptographic PRNG::::TAXONOMY NAME:CERT C Secure Coding:ENTRY ID:MSC30-C:ENTRY NAME:Do not use the rand() function for generating pseudorandom numbers:MAPPING FIT:CWE More Abstract::"));
this.cweList.put(
297,
new CWE(
297,
"Improper Validation of Certificate with Host Mismatch",
"Variant",
"Incomplete",
"The software communicates with a host that provides a certificate, but the software does not properly ensure that the certificate is actually associated with that host.\nEven if a certificate is well-formed, signed, and follows the chain of trust, it may simply be a valid certificate for a different site than the site that the software is interacting with. If the certificate's host-specific data is not properly checked - such as the Common Name (CN) in the Subject or the Subject Alternative Name (SAN) extension of an X.509 certificate - it may be possible for a redirection or spoofing attack to allow a malicious host with a valid certificate to provide data, impersonating a trusted host. In order to ensure data integrity, the certificate must be valid and it must pertain to the site that is being accessed. Even if the software attempts to check the hostname, it is still possible to incorrectly check the hostname. For example, attackers could create a certificate with a name that begins with a trusted name followed by a NUL byte, which could cause some string-based comparisons to only examine the portion that contains the trusted name. This weakness can occur even when the software uses Certificate Pinning, if the software does not verify the hostname at the time a certificate is pinned.\n::NATURE:ChildOf:CWE ID:295:VIEW ID:1000::NATURE:ChildOf:CWE ID:295:VIEW ID:699:ORDINAL:Primary::NATURE:ChildOf:CWE ID:295:VIEW ID:1003:ORDINAL:Primary::NATURE:ChildOf:CWE ID:923:VIEW ID:1000:ORDINAL:Primary::\n:::LANGUAGE CLASS:Language-Independent:LANGUAGE PREVALENCE:Undetermined::PARADIGN NAME:Mobile:PARADIGN PREVALENCE:Undetermined::\n:::PHASE:Architecture and Design:DESCRIPTION::::PHASE:Implementation:DESCRIPTION:::\n::SCOPE:Access Control:TECHNICAL IMPACT:Gain Privileges or Assume Identity:NOTE:Access Control Gain Privileges or Assume Identity The data read from the system vouched for by the certificate may not be from the expected system.::SCOPE:Authentication:SCOPE:Other:TECHNICAL IMPACT:Other:NOTE:Authentication Other Other Trust afforded to the system in question - based on the malicious certificate - may allow for spoofing or redirection attacks.::\n::METHOD:Dynamic Analysis with Manual Results Interpretation:EFFECTIVENESS::DESCRIPTION:Set up an untrusted endpoint (e.g. a server) with which the software will connect. Create a test certificate that uses an invalid hostname but is signed by a trusted CA and provide this certificate from the untrusted endpoint. If the software performs any operations instead of disconnecting and reporting an error, then this indicates that the hostname is not being checked and the test certificate has been accepted.::METHOD:Black Box:EFFECTIVENESS::DESCRIPTION:When Certificate Pinning is being used in a mobile application, consider using a tool such as Spinner [REF-955]. This methodology might be extensible to other technologies.::\n::PHASE:Architecture and Design:STRATEGY::EFFECTIVENESS::DESCRIPTION:Fully check the hostname of the certificate and provide the user with adequate information about the nature of the problem and how to proceed.::PHASE:Implementation:STRATEGY::EFFECTIVENESS::DESCRIPTION:If certificate pinning is being used, ensure that all relevant properties of the certificate are fully validated before the certificate is pinned, including the hostname.::\n::REFERENCE:CVE-2012-5810:DESCRIPTION:Mobile banking application does not verify hostname, leading to financial loss.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5810REFERENCE:CVE-2012-5811:DESCRIPTION:Mobile application for printing documents does not verify hostname, allowing attackers to read sensitive documents.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5811REFERENCE:CVE-2012-5807:DESCRIPTION:Software for electronic checking does not verify hostname, leading to financial loss.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5807REFERENCE:CVE-2012-3446:DESCRIPTION:Cloud-support library written in Python uses incorrect regular expression when matching hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-3446REFERENCE:CVE-2009-2408:DESCRIPTION:Web browser does not correctly handle '0' character (NUL) in Common Name, allowing spoofing of https sites.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-2408REFERENCE:CVE-2012-0867:DESCRIPTION:Database program truncates the Common Name during hostname verification, allowing spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-0867REFERENCE:CVE-2010-2074:DESCRIPTION:Incorrect handling of '0' character (NUL) in hostname verification allows spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2010-2074REFERENCE:CVE-2009-4565:DESCRIPTION:Mail server's incorrect handling of '0' character (NUL) in hostname verification allows spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-4565REFERENCE:CVE-2009-3767:DESCRIPTION:LDAP server's incorrect handling of '0' character (NUL) in hostname verification allows spoofing.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3767REFERENCE:CVE-2012-5806:DESCRIPTION:Payment processing module does not verify hostname when connecting to PayPal using PHP fsockopen function.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5806REFERENCE:CVE-2012-2993:DESCRIPTION:Smartphone device does not verify hostname, allowing spoofing of mail services.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2993REFERENCE:CVE-2012-5804:DESCRIPTION:E-commerce module does not verify hostname when connecting to payment site.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5804REFERENCE:CVE-2012-5824:DESCRIPTION:Chat application does not validate hostname, leading to loss of privacy.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5824REFERENCE:CVE-2012-5822:DESCRIPTION:Application uses third-party library that does not validate hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5822REFERENCE:CVE-2012-5819:DESCRIPTION:Cloud storage management application does not validate hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5819REFERENCE:CVE-2012-5817:DESCRIPTION:Java library uses JSSE SSLSocket and SSLEngine classes, which do not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5817REFERENCE:CVE-2012-5784:DESCRIPTION:SOAP platform does not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5784REFERENCE:CVE-2012-5782:DESCRIPTION:PHP library for payments does not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5782REFERENCE:CVE-2012-5780:DESCRIPTION:Merchant SDK for payments does not verify the hostname.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-5780REFERENCE:CVE-2003-0355:DESCRIPTION:Web browser does not validate Common Name, allowing spoofing of https sites.:LINK:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2003-0355\nTAXONOMY NAME:CLASP:ENTRY NAME:Failure to validate host-specific certificate data::"));
}
/**
* The lookup for the CWE
*
* <p>CWE_Lookup({@link java.lang.Integer})
*
* @param cweId {@link java.lang.Integer}
* @return a {@link CWE_Reader.CWE} object.
*/
public CWE CWE_Lookup(Integer cweId) {
if (this.getCweList().containsKey(cweId)) return this.cweList.get(cweId);
else return this.cweList.get(-1);
}
/**
* Getter for the field <code>cweVersion</code>.
*
* @return a {@link java.lang.Double} object.
*/
public Double getCweVersion() {
return this.cweVersion;
}
//endregion
}
| 44,061 | 269.319018 | 9,427 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/BaseAnalyzer.java | /* Licensed under GPL-3.0 */
package analyzer;
import analyzer.backward.Analysis;
import analyzer.backward.MethodWrapper;
import analyzer.backward.UnitContainer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import rule.base.BaseRuleChecker;
import slicer.backward.MethodCallSiteInfo;
import slicer.backward.SlicingCriteria;
import slicer.backward.method.MethodInfluenceInstructions;
import slicer.backward.method.MethodSlicingResult;
import slicer.backward.property.PropertyAnalysisResult;
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.UnitGraph;
import util.FieldInitializationInstructionMap;
import util.NamedMethodMap;
import util.Utils;
/**
* BaseAnalyzer class.
*
* @author CryptoguardTeam
* @version 03.07.01
* @since V01.00.00
*/
public class BaseAnalyzer {
/** Constant <code>CRITERIA_CLASSES</code> */
public static final List<String> CRITERIA_CLASSES = new ArrayList<>();
private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(BaseAnalyzer.class);
static {
CRITERIA_CLASSES.add("javax.crypto.Cipher");
CRITERIA_CLASSES.add("java.security.MessageDigest");
CRITERIA_CLASSES.add("javax.crypto.spec.SecretKeySpec");
CRITERIA_CLASSES.add("javax.crypto.spec.PBEKeySpec");
CRITERIA_CLASSES.add("java.security.KeyPairGenerator");
CRITERIA_CLASSES.add("java.net.URL");
CRITERIA_CLASSES.add("okhttp3.Request$Builder");
CRITERIA_CLASSES.add("retrofit2.Retrofit$Builder");
CRITERIA_CLASSES.add("javax.crypto.spec.PBEParameterSpec");
CRITERIA_CLASSES.add("javax.crypto.spec.IvParameterSpec");
CRITERIA_CLASSES.add("java.security.KeyStore");
CRITERIA_CLASSES.add("java.security.SecureRandom");
}
static void analyzeSliceInternal(
String criteriaClass,
List<String> classNames,
String endPoint,
ArrayList<Integer> slicingParameters,
BaseRuleChecker checker) {
SootClass criteriaClazz = Scene.v().getSootClass(criteriaClass);
if (criteriaClazz.isPhantomClass()
|| !criteriaClazz.getMethods().toString().contains(endPoint)) {
return;
}
NamedMethodMap.build(classNames);
NamedMethodMap.addCriteriaClasses(CRITERIA_CLASSES);
NamedMethodMap.buildCallerCalleeRelation(classNames);
FieldInitializationInstructionMap.build(classNames);
runBackwardSlicingAnalysis(
NamedMethodMap.getMethod(endPoint), slicingParameters, null, null, checker);
}
private static void runBackwardSlicingAnalysis(
MethodWrapper criteria,
List<Integer> slicingParams,
Map<MethodWrapper, List<Analysis>> methodVsAnalysisResult,
Map<SlicingCriteria, Boolean> slicingCriteriaMap,
BaseRuleChecker checker) {
List<MethodWrapper> callers = criteria.getCallerList();
if (callers.isEmpty() || slicingParams == null || slicingParams.isEmpty()) {
return;
}
List<MethodCallSiteInfo> callSites = new ArrayList<>();
for (MethodWrapper caller : callers) {
for (MethodCallSiteInfo site : caller.getCalleeList()) {
if (site.getCallee().toString().equals(criteria.toString())) {
callSites.add(site);
}
}
}
for (MethodCallSiteInfo callSiteInfo : callSites) {
SlicingCriteria slicingCriteria = new SlicingCriteria(callSiteInfo, slicingParams);
if (methodVsAnalysisResult == null) {
Map<MethodWrapper, List<Analysis>> newResult = new HashMap<>();
runBackwardSlicingAnalysisInternal(slicingCriteria, newResult, slicingCriteriaMap, checker);
for (MethodWrapper methodWrapper : newResult.keySet()) {
List<Analysis> analysisList = newResult.get(methodWrapper);
for (Analysis analysis : analysisList) {
if (!analysis.getAnalysisResult().isEmpty()) {
Utils.NUM_SLICES++;
Utils.SLICE_LENGTH.add(analysis.getAnalysisResult().size());
}
checker.analyzeSlice(analysis);
}
}
System.gc();
} else {
runBackwardSlicingAnalysisInternal(
slicingCriteria, methodVsAnalysisResult, slicingCriteriaMap, checker);
}
}
}
private static void runBackwardSlicingAnalysisInternal(
SlicingCriteria slicingCriteria,
Map<MethodWrapper, List<Analysis>> methodVsAnalysisResult,
Map<SlicingCriteria, Boolean> slicingCriteriaMap,
BaseRuleChecker checker) {
if (slicingCriteriaMap == null) {
slicingCriteriaMap = new HashMap<>();
}
MethodCallSiteInfo callSiteInfo = slicingCriteria.getMethodCallSiteInfo();
List<Integer> slicingParams = slicingCriteria.getParameters();
if (slicingCriteriaMap.get(slicingCriteria) != null) {
return;
}
slicingCriteriaMap.put(slicingCriteria, Boolean.TRUE);
MethodSlicingResult methodSlicingResult =
getInfluencingInstructions(
callSiteInfo, slicingParams, callSiteInfo.getCaller().getMethod());
if (methodSlicingResult.getPropertyUseMap() != null) {
for (String property : methodSlicingResult.getPropertyUseMap().keySet()) {
List<PropertyAnalysisResult> propertyAnalysisResults =
methodSlicingResult.getPropertyUseMap().get(property);
for (PropertyAnalysisResult propertyAnalysisResult : propertyAnalysisResults) {
List<Analysis> calleeAnalysisList = methodVsAnalysisResult.get(callSiteInfo.getCallee());
List<Analysis> callerAnalysisList =
methodVsAnalysisResult.get(propertyAnalysisResult.getMethodWrapper());
List<Analysis> newAnalysisList =
buildNewPropertyAnalysisList(
callSiteInfo,
methodSlicingResult.getAnalysisResult(),
propertyAnalysisResult,
calleeAnalysisList);
if (callerAnalysisList == null) {
callerAnalysisList = new ArrayList<>();
methodVsAnalysisResult.put(
propertyAnalysisResult.getMethodWrapper(), callerAnalysisList);
}
callerAnalysisList.addAll(newAnalysisList);
runBackwardSlicingAnalysis(
propertyAnalysisResult.getMethodWrapper(),
propertyAnalysisResult.getInfluencingParams(),
methodVsAnalysisResult,
slicingCriteriaMap,
checker);
}
}
}
List<Analysis> calleeAnalysisList = methodVsAnalysisResult.get(callSiteInfo.getCallee());
List<Analysis> callerAnalysisList = methodVsAnalysisResult.get(callSiteInfo.getCaller());
List<Analysis> newAnalysisList =
buildNewAnalysisList(
callSiteInfo, methodSlicingResult.getAnalysisResult(), calleeAnalysisList);
if (callerAnalysisList == null) {
callerAnalysisList = new ArrayList<>();
methodVsAnalysisResult.put(callSiteInfo.getCaller(), callerAnalysisList);
}
callerAnalysisList.addAll(newAnalysisList);
runBackwardSlicingAnalysis(
callSiteInfo.getCaller(),
methodSlicingResult.getInfluencingParameters(),
methodVsAnalysisResult,
slicingCriteriaMap,
checker);
}
private static List<Analysis> buildNewPropertyAnalysisList(
MethodCallSiteInfo callSiteInfo,
List<UnitContainer> methodSlicingResult,
PropertyAnalysisResult slicingResult,
List<Analysis> calleeAnalysisList) {
List<Analysis> newAnalysisList = new ArrayList<>();
if (calleeAnalysisList != null && !calleeAnalysisList.isEmpty()) {
for (Analysis analysis : calleeAnalysisList) {
Analysis newAnalysis = new Analysis();
String newChain =
callSiteInfo.getCaller()
+ "["
+ callSiteInfo.getLineNumber()
+ "]"
+ "--->"
+ callSiteInfo.getCallee()
+ "--->"
+ analysis.getMethodChain();
newAnalysis.setMethodChain(newChain);
newAnalysis.setAnalysisResult(analysis.getAnalysisResult());
newAnalysis.getAnalysisResult().addAll(methodSlicingResult);
newAnalysis.getAnalysisResult().addAll(slicingResult.getSlicingResult());
for (String key : slicingResult.getPropertyUseMap().keySet()) {
for (PropertyAnalysisResult res : slicingResult.getPropertyUseMap().get(key))
newAnalysis.getAnalysisResult().addAll(res.getSlicingResult());
}
newAnalysisList.add(newAnalysis);
}
} else {
Analysis newAnalysis = new Analysis();
String newChain =
callSiteInfo.getCaller()
+ "["
+ callSiteInfo.getLineNumber()
+ "]"
+ "--->"
+ callSiteInfo.getCallee();
newAnalysis.setMethodChain(newChain);
newAnalysis.setAnalysisResult(new ArrayList<>());
newAnalysis.getAnalysisResult().addAll(methodSlicingResult);
newAnalysis.getAnalysisResult().addAll(slicingResult.getSlicingResult());
for (String key : slicingResult.getPropertyUseMap().keySet()) {
for (PropertyAnalysisResult res : slicingResult.getPropertyUseMap().get(key))
newAnalysis.getAnalysisResult().addAll(res.getSlicingResult());
}
newAnalysisList.add(newAnalysis);
}
return newAnalysisList;
}
private static List<Analysis> buildNewAnalysisList(
MethodCallSiteInfo callSiteInfo,
List<UnitContainer> slicingResult,
List<Analysis> calleeAnalysisList) {
List<Analysis> newAnalysisList = new ArrayList<>();
if (calleeAnalysisList != null && !calleeAnalysisList.isEmpty()) {
for (Analysis analysis : calleeAnalysisList) {
Analysis newAnalysis = new Analysis();
String newChain =
callSiteInfo.getCaller()
+ "["
+ callSiteInfo.getLineNumber()
+ "]"
+ "--->"
+ analysis.getMethodChain();
newAnalysis.setMethodChain(newChain);
newAnalysis.setAnalysisResult(analysis.getAnalysisResult());
newAnalysis.getAnalysisResult().addAll(slicingResult);
newAnalysisList.add(newAnalysis);
}
} else {
Analysis newAnalysis = new Analysis();
String newChain =
callSiteInfo.getCaller()
+ "["
+ callSiteInfo.getLineNumber()
+ "]"
+ "--->"
+ callSiteInfo.getCallee();
newAnalysis.setMethodChain(newChain);
newAnalysis.setAnalysisResult(new ArrayList<>());
newAnalysis.getAnalysisResult().addAll(slicingResult);
newAnalysisList.add(newAnalysis);
}
return newAnalysisList;
}
private static MethodSlicingResult getInfluencingInstructions(
MethodCallSiteInfo methodCallSiteInfo, List<Integer> slicingParams, SootMethod m) {
Body b = m.retrieveActiveBody();
UnitGraph graph = new ExceptionalUnitGraph(b);
MethodInfluenceInstructions vbe =
new MethodInfluenceInstructions(graph, methodCallSiteInfo, slicingParams);
return vbe.getMethodSlicingResult();
}
}
| 11,254 | 33.630769 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/BaseAnalyzerRouting.java | /* Licensed under GPL-3.0 */
package analyzer;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import rule.base.BaseRuleChecker;
import rule.engine.EngineType;
import soot.Scene;
import soot.SootClass;
import soot.options.Options;
import util.Utils;
/**
* BaseAnalyzerRouting class.
*
* @author CryptoguardTeam Created on 2019-01-26.
* @version 03.07.01
* @since 02.02.00
* <p>The class to handle the routing for the different use cases.
*/
public class BaseAnalyzerRouting {
private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(BaseAnalyzerRouting.class);
/**
* environmentRouting.
*
* @param routingType a {@link rule.engine.EngineType} object.
* @param criteriaClass a {@link java.lang.String} object.
* @param criteriaMethod a {@link java.lang.String} object.
* @param criteriaParam a int.
* @param snippetPath a {@link java.util.List} object.
* @param projectDependency a {@link java.util.List} object.
* @param checker a {@link rule.base.BaseRuleChecker} object.
* @param mainKlass a {@link java.lang.String} object.
* @param androidHome a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static void environmentRouting(
EngineType routingType,
String criteriaClass,
String criteriaMethod,
int criteriaParam,
List<String> snippetPath,
List<String> projectDependency,
BaseRuleChecker checker,
String mainKlass,
String androidHome,
String javaHome)
throws ExceptionHandler {
switch (routingType) {
case JAR:
setupBaseJar(
criteriaClass,
criteriaMethod,
criteriaParam,
snippetPath.get(0),
projectDependency.size() >= 1 ? projectDependency.get(0) : null,
checker,
mainKlass,
javaHome);
break;
case APK:
setupBaseAPK(
criteriaClass,
criteriaMethod,
criteriaParam,
snippetPath.get(0),
checker,
mainKlass,
androidHome,
javaHome);
break;
case DIR:
setupBaseDir(
criteriaClass,
criteriaMethod,
criteriaParam,
snippetPath,
projectDependency,
checker,
mainKlass,
javaHome);
break;
case JAVAFILES:
setupBaseJava(
criteriaClass,
criteriaMethod,
criteriaParam,
snippetPath,
projectDependency,
checker,
mainKlass,
javaHome);
break;
case CLASSFILES:
setupBaseJavaClass(
criteriaClass,
criteriaMethod,
criteriaParam,
snippetPath,
projectDependency,
checker,
mainKlass,
javaHome);
break;
}
}
//region Case Handlers
//region JAR
/**
* setupBaseJar.
*
* @param criteriaClass a {@link java.lang.String} object.
* @param criteriaMethod a {@link java.lang.String} object.
* @param criteriaParam a int.
* @param projectJarPath a {@link java.lang.String} object.
* @param projectDependencyPath a {@link java.lang.String} object.
* @param checker a {@link rule.base.BaseRuleChecker} object.
* @param mainKlass a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static void setupBaseJar(
String criteriaClass,
String criteriaMethod,
int criteriaParam,
String projectJarPath,
String projectDependencyPath,
BaseRuleChecker checker,
String mainKlass,
String javaHome)
throws ExceptionHandler {
List<String> classNames = Utils.getClassNamesFromJarArchive(projectJarPath);
for (String dependency : Utils.getJarsInDirectory(projectDependencyPath))
classNames.addAll(Utils.getClassNamesFromJarArchive(dependency));
Scene.v()
.setSootClassPath(
Utils.join(
":",
projectJarPath,
Utils.getBaseSoot(javaHome),
Utils.join(":", Utils.getJarsInDirectory(projectDependencyPath))));
log.debug("Setting the soot class path as: " + Scene.v().getSootClassPath());
loadBaseSootInfo(classNames, criteriaClass, criteriaMethod, criteriaParam, checker, "_JAR_");
}
//endregion
//region APK
/**
* setupBaseAPK.
*
* @param criteriaClass a {@link java.lang.String} object.
* @param criteriaMethod a {@link java.lang.String} object.
* @param criteriaParam a int.
* @param projectJarPath a {@link java.lang.String} object.
* @param checker a {@link rule.base.BaseRuleChecker} object.
* @param mainKlass a {@link java.lang.String} object.
* @param androidHome a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static void setupBaseAPK(
String criteriaClass,
String criteriaMethod,
int criteriaParam,
String projectJarPath,
BaseRuleChecker checker,
String mainKlass,
String androidHome,
String javaHome)
throws ExceptionHandler {
List<String> classNames = Utils.getClassNamesFromApkArchive(projectJarPath);
//enables multi-dex support for soot
Options.v().set_process_multiple_dex(true);
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_android_jars(Utils.osPathJoin(androidHome, "platforms"));
Options.v().set_soot_classpath(Utils.getBaseSoot(javaHome));
Options.v().set_process_dir(Collections.singletonList(projectJarPath));
Options.v().set_whole_program(true);
loadBaseSootInfo(classNames, criteriaClass, criteriaMethod, criteriaParam, checker, "_APK_");
}
//endregion
//region BaseDir
/**
* setupBaseDir.
*
* @param criteriaClass a {@link java.lang.String} object.
* @param criteriaMethod a {@link java.lang.String} object.
* @param criteriaParam a int.
* @param snippetPath a {@link java.util.List} object.
* @param projectDependency a {@link java.util.List} object.
* @param checker a {@link rule.base.BaseRuleChecker} object.
* @param mainKlass a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static void setupBaseDir(
String criteriaClass,
String criteriaMethod,
int criteriaParam,
List<String> snippetPath,
List<String> projectDependency,
BaseRuleChecker checker,
String mainKlass,
String javaHome)
throws ExceptionHandler {
Options.v().set_output_format(Options.output_format_jimple);
Options.v().set_src_prec(Options.src_prec_java);
Scene.v()
.setSootClassPath(
Utils.getBaseSoot(javaHome)
+ ":"
+ Utils.join(":", snippetPath)
+ ":"
+ Utils.buildSootClassPath(projectDependency));
List<String> classNames = Utils.getClassNamesFromSnippet(snippetPath);
loadBaseSootInfo(classNames, criteriaClass, criteriaMethod, criteriaParam, checker, "_DIR_");
}
//endregion
//region JavaFiles
//Like Dir
/**
* setupBaseJava.
*
* @param criteriaClass a {@link java.lang.String} object.
* @param criteriaMethod a {@link java.lang.String} object.
* @param criteriaParam a int.
* @param snippetPath a {@link java.util.List} object.
* @param projectDependency a {@link java.util.List} object.
* @param checker a {@link rule.base.BaseRuleChecker} object.
* @param mainKlass a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static void setupBaseJava(
String criteriaClass,
String criteriaMethod,
int criteriaParam,
List<String> snippetPath,
List<String> projectDependency,
BaseRuleChecker checker,
String mainKlass,
String javaHome)
throws ExceptionHandler {
Options.v().set_src_prec(Options.src_prec_java);
Options.v().set_output_format(Options.output_format_jimple);
Options.v().set_verbose(true);
Options.v().set_validate(true);
Options.v().set_whole_program(true);
List<String> classNames = Utils.retrieveFullyQualifiedName(snippetPath);
Scene.v()
.setSootClassPath(
Utils.surround(
":",
Utils.getBaseSoot(javaHome),
Utils.joinSpecialSootClassPath(snippetPath),
Utils.buildSootClassPath(projectDependency)));
log.debug("Setting the soot class path as: " + Scene.v().getSootClassPath());
for (String dependency : Utils.getJarsInDirectories(projectDependency)) {
classNames.addAll(Utils.getClassNamesFromJarArchive(dependency));
}
loadBaseSootInfo(classNames, criteriaClass, criteriaMethod, criteriaParam, checker, mainKlass);
}
//endregion
//region JavaClassFiles
//Like Jar
/**
* setupBaseJavaClass.
*
* @param criteriaClass a {@link java.lang.String} object.
* @param criteriaMethod a {@link java.lang.String} object.
* @param criteriaParam a int.
* @param sourceJavaClasses a {@link java.util.List} object.
* @param projectDependencyPath a {@link java.util.List} object.
* @param checker a {@link rule.base.BaseRuleChecker} object.
* @param mainKlass a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static void setupBaseJavaClass(
String criteriaClass,
String criteriaMethod,
int criteriaParam,
List<String> sourceJavaClasses,
List<String> projectDependencyPath,
BaseRuleChecker checker,
String mainKlass,
String javaHome)
throws ExceptionHandler {
Options.v().set_src_prec(Options.src_prec_only_class);
Options.v().set_output_format(Options.output_format_jimple);
Options.v().set_verbose(true);
Options.v().set_validate(true);
Options.v().set_whole_program(true);
List<String> classNames = Utils.retrieveFullyQualifiedName(sourceJavaClasses);
Scene.v()
.setSootClassPath(
Utils.surround(
":",
Utils.joinSpecialSootClassPath(sourceJavaClasses),
Utils.getBaseSoot(javaHome),
Utils.join(":", Utils.getJarsInDirectories(projectDependencyPath))));
log.debug("Setting the soot class path as: " + Scene.v().getSootClassPath());
for (String clazz : classNames) {
log.debug("Working with the full class path: " + clazz);
Options.v().classes().add(clazz);
}
for (String dependency : Utils.getJarsInDirectories(projectDependencyPath))
classNames.addAll(Utils.getClassNamesFromJarArchive(dependency));
loadBaseSootInfo(classNames, criteriaClass, criteriaMethod, criteriaParam, checker, mainKlass);
}
//endregion
/**
* loadBaseSootInfo.
*
* @param classNames a {@link java.util.List} object.
* @param criteriaClass a {@link java.lang.String} object.
* @param criteriaMethod a {@link java.lang.String} object.
* @param criteriaParam a int.
* @param checker a {@link rule.base.BaseRuleChecker} object.
* @param mainKlass a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static void loadBaseSootInfo(
List<String> classNames,
String criteriaClass,
String criteriaMethod,
int criteriaParam,
BaseRuleChecker checker,
String mainKlass)
throws ExceptionHandler {
Options.v().set_keep_line_number(true);
Options.v().set_allow_phantom_refs(true);
List<String> ignoreLibs =
Arrays.asList("okhttp3.Request$Builder", "retrofit2.Retrofit$Builder");
for (String clazz : BaseAnalyzer.CRITERIA_CLASSES) {
log.debug("Loading with the class: " + clazz);
try {
SootClass runningClass;
if ((runningClass = Scene.v().loadClassAndSupport(clazz)).isPhantom()
&& !ignoreLibs.contains(runningClass.getName())) {
log.fatal("Class: " + clazz + " is not properly loaded");
throw new ExceptionHandler(
"Class: " + clazz + " is not properly loaded", ExceptionId.LOADING);
}
log.debug("Successfully loaded the class: " + clazz);
} catch (ExceptionHandler e) {
throw e;
} catch (Error | Exception e) {
log.fatal("Error loading Class: " + clazz);
throw new ExceptionHandler("Error loading Class: " + clazz, ExceptionId.LOADING);
}
}
boolean mainMethodFound = false;
boolean avoidMainKlass =
StringUtils.isNotEmpty(mainKlass)
&& !mainKlass.equals("_JAR_")
&& !mainKlass.equals("_APK_")
&& !mainKlass.equals("_DIR_");
for (String clazz : classNames) {
log.debug("Working with the internal class path: " + clazz);
try {
SootClass runningClass = Scene.v().loadClassAndSupport(clazz);
if (runningClass.isPhantom()) {
log.fatal("Class: " + clazz + " is not properly loaded");
throw new ExceptionHandler(
"Class " + clazz + " is not properly loaded", ExceptionId.LOADING);
}
boolean containsMain =
runningClass.getMethods().stream().anyMatch(m -> m.getName().equals("main"));
if (!mainMethodFound) mainMethodFound = containsMain;
else if (avoidMainKlass && containsMain && StringUtils.isEmpty(mainKlass)) {
log.fatal("Multiple Entry-points (main) found within the files included.");
throw new ExceptionHandler(
"Multiple Entry-points (main) found within the files included.",
ExceptionId.FILE_READ);
}
log.debug("Successfully loaded the Class: " + clazz);
} catch (ExceptionHandler e) {
throw e;
} catch (Error | Exception e) {
log.fatal("Error loading class " + clazz);
throw new ExceptionHandler("Error loading class " + clazz, ExceptionId.LOADING);
}
}
Scene.v().loadNecessaryClasses();
Scene.v().setDoneResolving();
Options.v().set_prepend_classpath(true);
Options.v().set_no_bodies_for_excluded(true);
if ((StringUtils.isNotEmpty(mainKlass) && avoidMainKlass)
&& (!Scene.v().hasMainClass()
|| classNames
.stream()
.noneMatch(str -> str.equals(Scene.v().getMainClass().getName())))) {
log.fatal(
"Could not detected an entry-point (main method) within any of the files provided.");
throw new ExceptionHandler(
"Could not detected an entry-point (main method) within any of the files provided.",
ExceptionId.FILE_READ);
}
if (StringUtils.isNotEmpty(mainKlass)
&& avoidMainKlass
&& !Scene.v().getMainClass().getName().equals(mainKlass)) {
SootClass mainClass = null;
try {
mainClass = Scene.v().getSootClass(Utils.retrieveFullyQualifiedName(mainKlass));
} catch (RuntimeException e) {
log.fatal("The class " + mainKlass + " was not loaded correctly.");
throw new ExceptionHandler(
"The class " + mainKlass + " was not loaded correctly.", ExceptionId.LOADING);
}
try {
Scene.v().setMainClass(mainClass);
} catch (RuntimeException e) {
log.fatal("The class " + mainKlass + " does not have a main method.");
throw new ExceptionHandler(
"The class " + mainKlass + " does not have a main method.", ExceptionId.LOADING);
}
}
String endPoint = "<" + criteriaClass + ": " + criteriaMethod + ">";
ArrayList<Integer> slicingParameters = new ArrayList<>();
slicingParameters.add(criteriaParam);
log.debug("Starting the slicer");
BaseAnalyzer.analyzeSliceInternal(
criteriaClass, classNames, endPoint, slicingParameters, checker);
}
}
| 16,694 | 33.493802 | 99 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/UniqueRuleAnalyzer.java | /* Licensed under GPL-3.0 */
package analyzer;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import rule.*;
import rule.engine.EngineType;
import soot.Scene;
import soot.options.Options;
import util.Utils;
/**
* UniqueRuleAnalyzer class.
*
* @author CryptoguardTeam Created on 2019-01-25.
* @version 03.07.01
* @since 02.00.04
* <p>The funneling class to handle the various different implementations of setting up the SOOT
* environment
* <p>Used for the following rules...
* <ol>
* <li>{@link UntrustedPrngFinder UntrustedPrngFinder}
* <li>{@link SSLSocketFactoryFinder SSLSocketFactoryFinder}
* <li>{@link CustomTrustManagerFinder CustomTrustManagerFinder}
* <li>{@link HostNameVerifierFinder HostNameVerifierFinder}
* <li>{@link DefaultExportGradeKeyFinder DefaultExportGradeKeyFinder}
* </ol>
*/
public class UniqueRuleAnalyzer {
/**
* environmentRouting.
*
* @param projectJarPath a {@link java.util.List} object.
* @param projectDependencyPath a {@link java.util.List} object.
* @param routingType a {@link rule.engine.EngineType} object.
* @param androidHome a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static List<String> environmentRouting(
List<String> projectJarPath,
List<String> projectDependencyPath,
EngineType routingType,
String androidHome,
String javaHome)
throws ExceptionHandler {
if (routingType == EngineType.JAR) {
return setupBaseJarEnv(
projectJarPath.get(0),
projectDependencyPath.size() >= 1 ? projectDependencyPath.get(0) : null,
javaHome);
} else if (routingType == EngineType.APK) {
return setupBaseAPKEnv(projectJarPath.get(0), androidHome, javaHome);
} else if (routingType == EngineType.DIR) {
return setupBaseSourceEnv(projectJarPath, projectDependencyPath, javaHome);
} else if (routingType == EngineType.JAVAFILES) {
return setupJavaFileEnv(projectJarPath, projectDependencyPath, javaHome);
} else { //if (routingType == EngineType.JAVACLASSFILES)
return setupJavaClassFileEnv(projectJarPath, projectDependencyPath, javaHome);
}
}
/**
* setupBaseJarEnv.
*
* @param projectJarPath a {@link java.lang.String} object.
* @param projectDependencyPath a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static List<String> setupBaseJarEnv(
String projectJarPath, String projectDependencyPath, String javaHome)
throws ExceptionHandler {
List<String> sootPaths = new ArrayList<>();
sootPaths.add(projectJarPath);
sootPaths.add(Utils.osPathJoin(javaHome, "jre", "lib", "rt.jar"));
sootPaths.add(Utils.osPathJoin(javaHome, "jre", "lib", "jce.jar"));
if (projectDependencyPath != null) sootPaths.add(projectJarPath);
Scene.v().setSootClassPath(Utils.buildSootClassPath(sootPaths));
Utils.loadSootClasses(null);
return Utils.getClassNamesFromJarArchive(projectJarPath);
}
/**
* setupBaseAPKEnv.
*
* @param projectJarPath a {@link java.lang.String} object.
* @param androidHome a {@link java.lang.String} object.
* @param javaHome a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static List<String> setupBaseAPKEnv(
String projectJarPath, String androidHome, String javaHome) throws ExceptionHandler {
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_android_jars(Utils.osPathJoin(androidHome, "platforms"));
Options.v().set_soot_classpath(Utils.getBaseSoot(javaHome));
Options.v().set_process_dir(Collections.singletonList(projectJarPath));
Options.v().set_whole_program(true);
Utils.loadSootClasses(null);
return Utils.getClassNamesFromApkArchive(projectJarPath);
}
/**
* setupBaseSourceEnv.
*
* @param snippetPath a {@link java.util.List} object.
* @param projectDependencyPath a {@link java.util.List} object.
* @param javaHome a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static List<String> setupBaseSourceEnv(
List<String> snippetPath, List<String> projectDependencyPath, String javaHome)
throws ExceptionHandler {
List<String> classNames = Utils.getClassNamesFromSnippet(snippetPath);
String srcPaths = String.join(":", snippetPath);
Options.v()
.set_soot_classpath(
Utils.getBaseSoot(javaHome)
+ ":"
+ srcPaths
+ Utils.buildSootClassPath(projectDependencyPath));
Options.v().set_output_format(Options.output_format_jimple);
Options.v().set_src_prec(Options.src_prec_java);
Utils.loadSootClasses(classNames);
return classNames;
}
//region Java Files
//Like Dir
/**
* setupJavaFileEnv.
*
* @param snippetPath a {@link java.util.List} object.
* @param projectDependencyPath a {@link java.util.List} object.
* @param javaHome a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static List<String> setupJavaFileEnv(
List<String> snippetPath, List<String> projectDependencyPath, String javaHome)
throws ExceptionHandler {
List<String> classNames = Utils.retrieveFullyQualifiedName(snippetPath);
StringBuilder sootPath = new StringBuilder();
sootPath.append(Utils.getBaseSoot(javaHome)).append(":").append(String.join(":", snippetPath));
if (projectDependencyPath.size() >= 1) {
List<String> classPaths = Utils.retrieveTrimmedSourcePaths(snippetPath);
sootPath.append(
Utils.buildSootClassPath(
Utils.retrieveBaseSourcePath(classPaths, projectDependencyPath.get(0))));
}
Options.v().set_soot_classpath(sootPath.toString());
Options.v().set_output_format(Options.output_format_jimple);
Options.v().set_src_prec(Options.src_prec_java);
Utils.loadSootClasses(classNames);
return classNames;
}
//endregion
//region JavaClassFiles
//Like Jar
/**
* setupJavaClassFileEnv.
*
* @param javaClassFiles a {@link java.util.List} object.
* @param projectDependencyPath a {@link java.util.List} object.
* @param javaHome a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static List<String> setupJavaClassFileEnv(
List<String> javaClassFiles, List<String> projectDependencyPath, String javaHome)
throws ExceptionHandler {
Scene.v().setSootClassPath(Utils.getBaseSoot(javaHome));
List<String> classNames = new ArrayList<>();
for (String in : javaClassFiles) classNames.add(Utils.retrieveFullyQualifiedName(in));
Utils.loadSootClasses(null);
return classNames;
}
//endregion
}
| 7,475 | 33.451613 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/backward/Analysis.java | /* Licensed under GPL-3.0 */
package analyzer.backward;
import java.util.List;
/**
* Analysis class.
*
* @author CryptoguardTeam
* @version 03.07.01
* @since V01.00.00
*/
public class Analysis {
private String methodChain;
private List<UnitContainer> analysisResult;
/**
* Getter for the field <code>methodChain</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getMethodChain() {
return methodChain;
}
/**
* Setter for the field <code>methodChain</code>.
*
* @param methodChain a {@link java.lang.String} object.
*/
public void setMethodChain(String methodChain) {
this.methodChain = methodChain;
}
/**
* Getter for the field <code>analysisResult</code>.
*
* @return a {@link java.util.List} object.
*/
public List<UnitContainer> getAnalysisResult() {
return analysisResult;
}
/**
* Setter for the field <code>analysisResult</code>.
*
* @param analysisResult a {@link java.util.List} object.
*/
public void setAnalysisResult(List<UnitContainer> analysisResult) {
this.analysisResult = analysisResult;
}
}
| 1,132 | 20.377358 | 69 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/backward/AssignInvokeUnitContainer.java | /* Licensed under GPL-3.0 */
package analyzer.backward;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* AssignInvokeUnitContainer class.
*
* @author franceme
* @version 03.07.01
*/
public class AssignInvokeUnitContainer extends UnitContainer {
private List<Integer> args = new ArrayList<>();
private Set<String> properties = new HashSet<>();
private List<UnitContainer> analysisResult = new ArrayList<>();
/**
* Getter for the field <code>args</code>.
*
* @return a {@link java.util.List} object.
*/
public List<Integer> getArgs() {
return args;
}
/**
* Setter for the field <code>args</code>.
*
* @param args a {@link java.util.List} object.
*/
public void setArgs(List<Integer> args) {
this.args = args;
}
/**
* Getter for the field <code>properties</code>.
*
* @return a {@link java.util.Set} object.
*/
public Set<String> getProperties() {
return properties;
}
/**
* Setter for the field <code>properties</code>.
*
* @param properties a {@link java.util.Set} object.
*/
public void setProperties(Set<String> properties) {
this.properties = properties;
}
/**
* Getter for the field <code>analysisResult</code>.
*
* @return a {@link java.util.List} object.
*/
public List<UnitContainer> getAnalysisResult() {
return analysisResult;
}
/**
* Setter for the field <code>analysisResult</code>.
*
* @param analysisResult a {@link java.util.List} object.
*/
public void setAnalysisResult(List<UnitContainer> analysisResult) {
this.analysisResult = analysisResult;
}
}
| 1,672 | 21.608108 | 69 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/backward/InvokeUnitContainer.java | /* Licensed under GPL-3.0 */
package analyzer.backward;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* InvokeUnitContainer class.
*
* @author franceme
* @version 03.07.01
*/
public class InvokeUnitContainer extends UnitContainer {
private List<Integer> args = new ArrayList<>();
private Set<String> definedFields = new HashSet<>();
private List<UnitContainer> analysisResult = new ArrayList<>();
/**
* Getter for the field <code>args</code>.
*
* @return a {@link java.util.List} object.
*/
public List<Integer> getArgs() {
return args;
}
/**
* Setter for the field <code>args</code>.
*
* @param args a {@link java.util.List} object.
*/
public void setArgs(List<Integer> args) {
this.args = args;
}
/**
* Getter for the field <code>definedFields</code>.
*
* @return a {@link java.util.Set} object.
*/
public Set<String> getDefinedFields() {
return definedFields;
}
/**
* Setter for the field <code>definedFields</code>.
*
* @param definedFields a {@link java.util.Set} object.
*/
public void setDefinedFields(Set<String> definedFields) {
this.definedFields = definedFields;
}
/**
* Getter for the field <code>analysisResult</code>.
*
* @return a {@link java.util.List} object.
*/
public List<UnitContainer> getAnalysisResult() {
return analysisResult;
}
/**
* Setter for the field <code>analysisResult</code>.
*
* @param analysisResult a {@link java.util.List} object.
*/
public void setAnalysisResult(List<UnitContainer> analysisResult) {
this.analysisResult = analysisResult;
}
}
| 1,691 | 21.56 | 69 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/backward/MethodWrapper.java | /* Licensed under GPL-3.0 */
package analyzer.backward;
import java.util.ArrayList;
import java.util.List;
import slicer.backward.MethodCallSiteInfo;
import soot.SootMethod;
/**
* Created by RigorityJTeam on 12/27/16.
*
* @author CryptoguardTeam
* @version 03.07.01
* @since V01.00.00
*/
public class MethodWrapper {
private boolean isTopLevel = true;
private SootMethod method;
private List<MethodCallSiteInfo> calleeList;
private List<MethodWrapper> callerList;
/**
* Constructor for MethodWrapper.
*
* @param method a {@link soot.SootMethod} object.
*/
public MethodWrapper(SootMethod method) {
this.method = method;
this.calleeList = new ArrayList<>();
this.callerList = new ArrayList<>();
}
/**
* Getter for the field <code>method</code>.
*
* @return a {@link soot.SootMethod} object.
*/
public SootMethod getMethod() {
return method;
}
/**
* Setter for the field <code>method</code>.
*
* @param method a {@link soot.SootMethod} object.
*/
public void setMethod(SootMethod method) {
this.method = method;
}
/**
* Getter for the field <code>calleeList</code>.
*
* @return a {@link java.util.List} object.
*/
public List<MethodCallSiteInfo> getCalleeList() {
return calleeList;
}
/**
* isTopLevel.
*
* @return a boolean.
*/
public boolean isTopLevel() {
return isTopLevel;
}
/**
* setTopLevel.
*
* @param topLevel a boolean.
*/
public void setTopLevel(boolean topLevel) {
isTopLevel = topLevel;
}
/**
* Getter for the field <code>callerList</code>.
*
* @return a {@link java.util.List} object.
*/
public List<MethodWrapper> getCallerList() {
return callerList;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MethodWrapper methodWrapper = (MethodWrapper) o;
return method.toString().equals(methodWrapper.method.toString());
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return method.toString().hashCode();
}
/** {@inheritDoc} */
@Override
public String toString() {
return method.toString();
}
}
| 2,255 | 19.509091 | 69 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/backward/ParamFakeUnitContainer.java | /* Licensed under GPL-3.0 */
package analyzer.backward;
/**
* ParamFakeUnitContainer class.
*
* @author CryptoguardTeam
* @version 03.07.01
* @since V01.00.00
*/
public class ParamFakeUnitContainer extends UnitContainer {
private int param;
private String callee;
/**
* Getter for the field <code>param</code>.
*
* @return a int.
*/
public int getParam() {
return param;
}
/**
* Setter for the field <code>param</code>.
*
* @param param a int.
*/
public void setParam(int param) {
this.param = param;
}
/**
* Getter for the field <code>callee</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getCallee() {
return callee;
}
/**
* Setter for the field <code>callee</code>.
*
* @param callee a {@link java.lang.String} object.
*/
public void setCallee(String callee) {
this.callee = callee;
}
}
| 919 | 16.692308 | 59 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/backward/PropertyFakeUnitContainer.java | /* Licensed under GPL-3.0 */
package analyzer.backward;
/**
* PropertyFakeUnitContainer class.
*
* @author CryptoguardTeam
* @version 03.07.01
* @since V01.00.00
*/
public class PropertyFakeUnitContainer extends UnitContainer {
private String originalProperty;
/**
* Getter for the field <code>originalProperty</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getOriginalProperty() {
return originalProperty;
}
/**
* Setter for the field <code>originalProperty</code>.
*
* @param originalProperty a {@link java.lang.String} object.
*/
public void setOriginalProperty(String originalProperty) {
this.originalProperty = originalProperty;
}
}
| 719 | 20.818182 | 63 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/backward/UnitContainer.java | /* Licensed under GPL-3.0 */
package analyzer.backward;
import soot.Unit;
/**
* UnitContainer class.
*
* @author CryptoguardTeam
* @version 03.07.01
* @since V01.00.00
*/
public class UnitContainer {
private Unit unit;
private String method;
/**
* Getter for the field <code>unit</code>.
*
* @return a {@link soot.Unit} object.
*/
public Unit getUnit() {
return unit;
}
/**
* Setter for the field <code>unit</code>.
*
* @param unit a {@link soot.Unit} object.
*/
public void setUnit(Unit unit) {
this.unit = unit;
}
/**
* Getter for the field <code>method</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getMethod() {
return method;
}
/**
* Setter for the field <code>method</code>.
*
* @param method a {@link java.lang.String} object.
*/
public void setMethod(String method) {
this.method = method;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UnitContainer that = (UnitContainer) o;
return unit.toString().equals(that.unit.toString());
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return ("UnitContainer{" + "unit=" + unit + ", method='" + method + "\'" + "}").hashCode();
}
/** {@inheritDoc} */
@Override
public String toString() {
return "UnitContainer{" + "unit=" + unit + ", method='" + method + '\'' + '}';
}
}
| 1,521 | 18.766234 | 95 | java |
cryptoguard | cryptoguard-master/src/main/java/analyzer/forward/MethodWrapper.java | /* Licensed under GPL-3.0 */
package analyzer.forward;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import slicer.forward.MethodCallSiteInfo;
import slicer.forward.SlicingResult;
import soot.SootMethod;
/**
* Created by RigorityJTeam on 12/27/16.
*
* @author CryptoguardTeam
* @version 03.07.01
* @since V01.00.00
*/
public class MethodWrapper {
private SootMethod method;
private List<MethodWrapper> calleeList;
private Map<MethodCallSiteInfo, SlicingResult> analysisListMap;
/**
* Constructor for MethodWrapper.
*
* @param method a {@link soot.SootMethod} object.
*/
public MethodWrapper(SootMethod method) {
this.method = method;
this.calleeList = new ArrayList<>();
this.analysisListMap = new HashMap<>();
}
/**
* Getter for the field <code>method</code>.
*
* @return a {@link soot.SootMethod} object.
*/
public SootMethod getMethod() {
return method;
}
/**
* Setter for the field <code>method</code>.
*
* @param method a {@link soot.SootMethod} object.
*/
public void setMethod(SootMethod method) {
this.method = method;
}
/**
* Getter for the field <code>calleeList</code>.
*
* @return a {@link java.util.List} object.
*/
public List<MethodWrapper> getCalleeList() {
return calleeList;
}
/**
* Setter for the field <code>calleeList</code>.
*
* @param calleeList a {@link java.util.List} object.
*/
public void setCalleeList(List<MethodWrapper> calleeList) {
this.calleeList = calleeList;
}
/**
* Getter for the field <code>analysisListMap</code>.
*
* @return a {@link java.util.Map} object.
*/
public Map<MethodCallSiteInfo, SlicingResult> getAnalysisListMap() {
return analysisListMap;
}
/**
* Setter for the field <code>analysisListMap</code>.
*
* @param analysisListMap a {@link java.util.Map} object.
*/
public void setAnalysisListMap(Map<MethodCallSiteInfo, SlicingResult> analysisListMap) {
this.analysisListMap = analysisListMap;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MethodWrapper methodWrapper = (MethodWrapper) o;
return method.toString().equals(methodWrapper.method.toString());
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return method.toString().hashCode();
}
/** {@inheritDoc} */
@Override
public String toString() {
return method.toString();
}
}
| 2,587 | 21.902655 | 90 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/argsIdentifier.java | /* Licensed under GPL-3.0 */
package frontEnd;
import frontEnd.MessagingSystem.routing.Listing;
import java.util.ArrayList;
import java.util.List;
import rule.engine.EngineType;
/**
* argsIdentifier class." -o " + tempFileOutApk_Scarf
*
* @author CryptoguardTeam Created on 2/5/19.
* @version 03.07.01
* @since 03.00.00
* <p>The central point for identifying the arguments and their description.
*/
public enum argsIdentifier {
//region Values
FORMAT(
"in",
"format",
"Required: The format of input you want to scan, available styles "
+ EngineType.retrieveEngineTypeValues()
+ ".",
"format",
null,
true),
SOURCE(
"s",
"file/files/*.in/dir/ClassPathString/xargs",
"Required: The source to be scanned use the absolute path or send all of the source files via the file input.in; ex. find -type f *.java >> input.in.",
"file(s)/*.in/dir",
null,
true),
DEPENDENCY("d", "dir", "The dependency to be scanned use the relative path.", "dir", null, false),
OUT(
"o",
"file",
"The file to be created with the output default will be the project name.",
"file",
null,
false),
NEW(
"new",
null,
"The file to be created with the output if existing will be overwritten.",
null,
null,
false),
TIMEMEASURE("t", null, "Output the time of the internal processes.", null, null, false),
FORMATOUT(
"m",
"formatType",
"The output format you want to produce, " + Listing.getShortHelp() + ".",
"formatType",
null,
true),
PRETTY("n", null, "Output the analysis information in a 'pretty' format.", null, null, false),
NOEXIT("X", null, "Upon completion of scanning, don't kill the JVM", null, null, false),
//EXPERIMENTRESULTS("exp", null, "View the experiment based results.", null, null, false),
VERSION("v", null, "Output the version number.", null, null, false),
NOLOGS("VX", null, "Display logs only from the fatal logs", null, null, false),
VERBOSE("V", null, "Display logs from debug levels", null, null, false),
VERYVERBOSE("VV", null, "Display logs from trace levels", null, null, false),
TIMESTAMP("ts", null, "Add a timestamp to the file output.", null, null, false),
DEPTH("depth", null, "The depth of slicing to go into", "depth", null, false),
//LOG("L", null, "Enable logging to the console.", null, null, false),
JAVA(
"java",
"envVariable",
"Directory of Java to be used JDK 7 for JavaFiles/Project and JDK 8 for ClassFiles/Jar",
"java",
null,
false),
ANDROID("android", "envVariable", "Specify of Android SDK", "android", null, false),
HEURISTICS(
"H", null, "The flag determining whether or not to display heuristics.", null, null, false),
STREAM("st", null, "Stream the analysis to the output file.", null, null, false),
HELP("h", null, "Print out the Help Information.", null, null, false),
MAIN(
"main",
"className",
"Choose the main class if there are multiple main classes in the files given.",
"main",
null,
false),
SCONFIG(
"Sconfig",
"file",
"Choose the Scarf property configuration file.",
"file.properties",
Listing.ScarfXML,
false),
SASSESSFW(
"Sassessfw", "variable", "The assessment framework", "variable", Listing.ScarfXML, false),
SASSESSFWVERSION(
"Sassessfwversion",
"variable",
"The assessment framework version",
"variable",
Listing.ScarfXML,
false),
SASSESSMENTSTARTTS(
"Sassessmentstartts",
"variable",
"The assessment start timestamp",
"variable",
Listing.ScarfXML,
false),
SBUILDFW("Sbuildfw", "variable", "The build framework", "variable", Listing.ScarfXML, false),
SBUILDFWVERSION(
"Sbuildfwversion",
"variable",
"The build framework version",
"variable",
Listing.ScarfXML,
false),
SBUILDROOTDIR(
"Sbuildrootdir", "dir", "The build root directory", "variable", Listing.ScarfXML, false),
SPACKAGENAME("Spackagename", "variable", "The package name", "variable", Listing.ScarfXML, false),
SPACKAGEROOTDIR(
"Spackagerootdir", "dir", "The package root directory", "variable", Listing.ScarfXML, false),
SPACKAGEVERSION(
"Spackageversion", "variable", "The package version", "variable", Listing.ScarfXML, false),
SPARSERFW("Sparserfw", "variable", "The parser framework", "variable", Listing.ScarfXML, false),
SPARSERFWVERSION(
"Sparserfwversion",
"variable",
"The parser framework version",
"variable",
Listing.ScarfXML,
false),
SUUID(
"Suuid",
"uuid",
"The uuid of the current pipeline progress",
"variable",
Listing.ScarfXML,
false);
//endregion
private String id;
private String defaultArg;
private String desc;
private Listing formatType;
private String argName;
private Boolean required;
argsIdentifier(
String id, String defaultArg, String desc, String argName, Listing format, Boolean required) {
this.id = id;
this.defaultArg = defaultArg;
this.desc = desc;
this.argName = argName;
this.formatType = format;
this.required = required;
}
/**
* lookup.
*
* @param id a {@link java.lang.String} object.
* @return a {@link frontEnd.argsIdentifier} object.
*/
public static argsIdentifier lookup(String id) {
for (argsIdentifier in : argsIdentifier.values()) if (in.getId().equals(id)) return in;
return null;
}
/**
* lookup.
*
* @param type a {@link frontEnd.MessagingSystem.routing.Listing} object.
* @return a {@link java.util.List} object.
*/
public static List<argsIdentifier> lookup(Listing type) {
List<argsIdentifier> args = new ArrayList<>();
for (argsIdentifier in : argsIdentifier.values())
if (in.formatType != null && in.formatType.equals(type)) args.add(in);
return args;
}
/**
* Getter for the field <code>id</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getId() {
return this.id;
}
/**
* getArg.
*
* @return a {@link java.lang.String} object.
*/
public String getArg() {
return "-" + this.id;
}
/**
* Getter for the field <code>desc</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getDesc() {
return this.name() + ": " + this.desc;
}
/**
* hasDefaultArg.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean hasDefaultArg() {
return defaultArg != null;
}
/**
* Getter for the field <code>defaultArg</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getDefaultArg() {
return defaultArg;
}
/**
* Getter for the field <code>formatType</code>.
*
* @return a {@link frontEnd.MessagingSystem.routing.Listing} object.
*/
public Listing getFormatType() {
return this.formatType;
}
/**
* Getter for the field <code>argName</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getArgName() {
return this.argName;
}
/**
* Getter for the field <code>required</code>.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean getRequired() {
return this.required;
}
}
| 7,409 | 27.72093 | 157 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/ArgumentsCheck.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import frontEnd.Interface.outputRouting.parcelHandling;
import frontEnd.Interface.parameterChecks.Core;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.Listing;
import frontEnd.argsIdentifier;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.cli.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import rule.engine.EngineType;
import util.Utils;
/**
* ArgumentsCheck class.
*
* @author CryptoguardTeam Created on 12/13/18.
* @version 03.07.01
* @since 01.01.02
* <p>The main check for the Arguments
*/
public class ArgumentsCheck {
private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(ArgumentsCheck.class);
/**
* The fail fast parameter Check method
*
* <p>This method will attempt to create the Environment Information and provide help if the usage
* doesn't match
*
* @param args {@link java.lang.String} - the raw arguments passed into the console
* @return {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} - when not null, the
* general Information is created for usage within any output structure.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static EnvironmentInformation paramaterCheck(List<String> args) throws ExceptionHandler {
//region CLI Section
List<String> originalArguments = new ArrayList<String>(args);
Options cmdLineArgs = setOptions();
CommandLine cmd = null;
//region Printing Version
if (args.contains(argsIdentifier.HELP.getArg())) {
throw new ExceptionHandler(
parcelHandling.retrieveHelpFromOptions(cmdLineArgs, null), ExceptionId.HELP);
}
if (args.contains(argsIdentifier.VERSION.getArg())) {
throw new ExceptionHandler(parcelHandling.retrieveHeaderInfo(), ExceptionId.VERSION);
}
//endregion
log.trace("Starting the parsing of arguments.");
try {
cmd = new DefaultParser().parse(cmdLineArgs, args.toArray(new String[0]), true);
} catch (ParseException e) {
log.debug("Issue with parsing the arguments: " + e.getMessage());
StringBuilder arg = null;
if (e.getMessage().startsWith("Missing required option: "))
arg =
new StringBuilder(
argsIdentifier
.lookup(e.getMessage().replace("Missing required option: ", ""))
.getArg());
else if (e.getMessage().startsWith("Missing required options: ")) {
String[] argIds =
e.getMessage().replace("Missing required options: ", "").replace(" ", "").split(",");
arg = new StringBuilder("Issue with the following argument(s) ");
for (String argId : argIds) arg.append(argsIdentifier.lookup(argId)).append(", ");
arg = new StringBuilder(arg.substring(0, arg.length() - ", ".length()));
}
log.fatal(parcelHandling.retrieveHelpFromOptions(cmdLineArgs, arg.toString()));
throw new ExceptionHandler(
parcelHandling.retrieveHelpFromOptions(cmdLineArgs, arg.toString()),
ExceptionId.ARG_VALID);
}
//endregion
//region Cleaning retrieved values from args
log.trace("Cleaning the extra output specific arguments.");
ArrayList<String> upgradedArgs = new ArrayList<>(args);
for (argsIdentifier arg : argsIdentifier.values()) {
if (cmd.hasOption(arg.getId())) {
upgradedArgs.remove("-" + arg.getId());
upgradedArgs.remove(cmd.getOptionValue(arg.getId()));
}
}
args = upgradedArgs;
log.debug("Output specific arguments: " + args.toString());
//endregion
EngineType type = EngineType.getFromFlag(cmd.getOptionValue(argsIdentifier.FORMAT.getId()));
log.debug("Chose the enginetype: " + type.getName());
//region Validating the Resources available based on the EngineType
//Needed regardless
String javaHome = null;
String androidHome = null;
switch (type) {
//Only APK path needs an android specified path
case APK:
if (cmd.hasOption(argsIdentifier.ANDROID.getArg()))
androidHome =
Utils.retrieveFilePath(
cmd.getOptionValue(argsIdentifier.ANDROID.getId()), null, false, false, true);
default:
if (cmd.hasOption(argsIdentifier.JAVA.getArg()))
javaHome =
Utils.retrieveFilePath(
cmd.getOptionValue(argsIdentifier.JAVA.getId()), null, false, false, true);
break;
}
//endregion
Boolean usingInputIn = cmd.getOptionValue(argsIdentifier.SOURCE.getId()).endsWith(".in");
log.debug("Enhanced Input in file: " + usingInputIn);
//region Logging Verbosity Check
if (cmd.hasOption(argsIdentifier.VERYVERBOSE.getArg())) {
Configurator.setRootLevel(Level.TRACE);
log.info("Displaying debug level logs");
} else if (cmd.hasOption(argsIdentifier.VERBOSE.getArg())) {
Configurator.setRootLevel(Level.DEBUG);
log.info("Displaying debug level logs");
} else if (cmd.hasOption(argsIdentifier.NOLOGS.getArg())) {
Configurator.setRootLevel(Level.OFF);
} else {
Configurator.setRootLevel(Level.INFO);
log.info("Displaying info level logs");
}
//endregion
//inputFiles
//region Setting the source files
List<String> source = Arrays.asList(cmd.getOptionValues(argsIdentifier.SOURCE.getId()));
String setMainClass = null;
if (cmd.hasOption(argsIdentifier.MAIN.getId())) {
setMainClass = StringUtils.trimToNull(cmd.getOptionValue(argsIdentifier.MAIN.getId()));
if (setMainClass == null) {
log.fatal("Please Enter a valid main class path.");
throw new ExceptionHandler("Please Enter a valid main class path.", ExceptionId.ARG_VALID);
}
}
//endregion
//region Setting the dependency path
List<String> dependencies =
cmd.hasOption(argsIdentifier.DEPENDENCY.getId())
? Arrays.asList(cmd.getOptionValues(argsIdentifier.DEPENDENCY.getId()))
: new ArrayList<>();
//endregion
Listing messaging =
Listing.retrieveListingType(cmd.getOptionValue(argsIdentifier.FORMATOUT.getId()));
log.info("Using the output: " + messaging.getType());
//region Setting the file out
log.trace("Determining the file out.");
String fileOutPath = null;
if (cmd.hasOption(argsIdentifier.OUT.getId()))
fileOutPath = cmd.getOptionValue(argsIdentifier.OUT.getId());
//endregion
EnvironmentInformation info =
Core.paramaterCheck(
source,
dependencies,
type,
messaging,
fileOutPath,
cmd.hasOption(argsIdentifier.NEW.getId()),
setMainClass,
cmd.hasOption(argsIdentifier.TIMESTAMP.getId()),
javaHome,
androidHome,
args);
//region Logging Information
info.setPrettyPrint(cmd.hasOption(argsIdentifier.PRETTY.getId()));
log.debug("Pretty flag: " + cmd.hasOption(argsIdentifier.PRETTY.getId()));
info.setShowTimes(cmd.hasOption(argsIdentifier.TIMEMEASURE.getId()));
log.debug("Time measure flag: " + cmd.hasOption(argsIdentifier.TIMEMEASURE.getId()));
info.setStreaming(cmd.hasOption(argsIdentifier.STREAM.getId()));
log.debug("Stream flag: " + cmd.hasOption(argsIdentifier.STREAM.getId()));
info.setDisplayHeuristics(cmd.hasOption(argsIdentifier.HEURISTICS.getId()));
log.debug("Heuristics flag: " + cmd.hasOption(argsIdentifier.HEURISTICS.getId()));
Utils.initDepth(
Integer.parseInt(cmd.getOptionValue(argsIdentifier.DEPTH.getId(), String.valueOf(1))));
log.debug("Scanning using a depth of " + Utils.DEPTH);
boolean noExitJVM = cmd.hasOption(argsIdentifier.NOEXIT.getId());
log.debug("Exiting the JVM: " + noExitJVM);
if (noExitJVM) info.setKillJVM(false);
//endregion
//Setting the raw command within info
info.setRawCommand(Utils.join(" ", originalArguments));
return info;
}
private static Options setOptions() {
Options cmdLineArgs = new Options();
//region General Options
Option format =
Option.builder(argsIdentifier.FORMAT.getId())
.required()
.hasArg()
.argName(argsIdentifier.FORMAT.getArgName())
.desc(argsIdentifier.FORMAT.getDesc())
.build();
format.setType(String.class);
format.setOptionalArg(argsIdentifier.FORMAT.getRequired());
cmdLineArgs.addOption(format);
Option sources =
Option.builder(argsIdentifier.SOURCE.getId())
.required()
.hasArgs()
.argName(argsIdentifier.SOURCE.getArgName())
.desc(argsIdentifier.SOURCE.getDesc())
.build();
sources.setType(String.class);
sources.setValueSeparator(' ');
sources.setOptionalArg(argsIdentifier.SOURCE.getRequired());
cmdLineArgs.addOption(sources);
Option dependency =
Option.builder(argsIdentifier.DEPENDENCY.getId())
.hasArg()
.argName(argsIdentifier.DEPENDENCY.getArgName())
.desc(argsIdentifier.DEPENDENCY.getDesc())
.build();
dependency.setType(String.class);
dependency.setOptionalArg(argsIdentifier.DEPENDENCY.getRequired());
cmdLineArgs.addOption(dependency);
Option mainFile =
Option.builder(argsIdentifier.MAIN.getId())
.hasArg()
.argName(argsIdentifier.MAIN.getArgName())
.desc(argsIdentifier.MAIN.getDesc())
.build();
mainFile.setType(String.class);
mainFile.setOptionalArg(argsIdentifier.MAIN.getRequired());
cmdLineArgs.addOption(mainFile);
Option javaPath =
Option.builder(argsIdentifier.JAVA.getId())
.hasArg()
.argName(argsIdentifier.JAVA.getArgName())
.desc(argsIdentifier.JAVA.getDesc())
.build();
javaPath.setType(File.class);
javaPath.setOptionalArg(argsIdentifier.JAVA.getRequired());
cmdLineArgs.addOption(javaPath);
Option androidPath =
Option.builder(argsIdentifier.ANDROID.getId())
.hasArg()
.argName(argsIdentifier.ANDROID.getArgName())
.desc(argsIdentifier.ANDROID.getDesc())
.build();
androidPath.setType(File.class);
androidPath.setOptionalArg(argsIdentifier.ANDROID.getRequired());
cmdLineArgs.addOption(androidPath);
Option depth =
Option.builder(argsIdentifier.DEPTH.getId())
.hasArg()
.argName(argsIdentifier.DEPTH.getArgName())
.desc(argsIdentifier.DEPTH.getDesc())
.build();
depth.setType(String.class);
depth.setOptionalArg(argsIdentifier.DEPTH.getRequired());
cmdLineArgs.addOption(depth);
Option output =
Option.builder(argsIdentifier.OUT.getId())
.hasArg()
.argName(argsIdentifier.OUT.getArgName())
.desc(argsIdentifier.OUT.getDesc())
.build();
output.setType(String.class);
output.setOptionalArg(argsIdentifier.OUT.getRequired());
cmdLineArgs.addOption(output);
Option timing =
new Option(argsIdentifier.TIMEMEASURE.getId(), false, argsIdentifier.TIMEMEASURE.getDesc());
timing.setOptionalArg(argsIdentifier.TIMEMEASURE.getRequired());
cmdLineArgs.addOption(timing);
Option formatOut =
Option.builder(argsIdentifier.FORMATOUT.getId())
.hasArg()
.argName(argsIdentifier.FORMATOUT.getArgName())
.desc(argsIdentifier.FORMATOUT.getDesc())
.build();
formatOut.setOptionalArg(argsIdentifier.FORMATOUT.getRequired());
cmdLineArgs.addOption(formatOut);
Option prettyPrint =
new Option(argsIdentifier.PRETTY.getId(), false, argsIdentifier.PRETTY.getDesc());
prettyPrint.setOptionalArg(argsIdentifier.PRETTY.getRequired());
cmdLineArgs.addOption(prettyPrint);
Option noExit =
new Option(argsIdentifier.NOEXIT.getId(), false, argsIdentifier.NOEXIT.getDesc());
noExit.setOptionalArg(argsIdentifier.NOEXIT.getRequired());
cmdLineArgs.addOption(noExit);
Option help = new Option(argsIdentifier.HELP.getId(), false, argsIdentifier.HELP.getDesc());
help.setOptionalArg(argsIdentifier.HELP.getRequired());
cmdLineArgs.addOption(help);
Option version =
new Option(argsIdentifier.VERSION.getId(), false, argsIdentifier.VERSION.getDesc());
version.setOptionalArg(argsIdentifier.VERSION.getRequired());
cmdLineArgs.addOption(version);
Option displayHeuristcs =
new Option(argsIdentifier.HEURISTICS.getId(), false, argsIdentifier.HEURISTICS.getDesc());
displayHeuristcs.setOptionalArg(argsIdentifier.HEURISTICS.getRequired());
cmdLineArgs.addOption(displayHeuristcs);
Option timeStamp =
new Option(argsIdentifier.TIMESTAMP.getId(), false, argsIdentifier.TIMESTAMP.getDesc());
timeStamp.setOptionalArg(argsIdentifier.TIMESTAMP.getRequired());
cmdLineArgs.addOption(timeStamp);
Option stream =
new Option(argsIdentifier.STREAM.getId(), false, argsIdentifier.STREAM.getDesc());
stream.setOptionalArg(argsIdentifier.STREAM.getRequired());
cmdLineArgs.addOption(stream);
Option nologs =
new Option(argsIdentifier.NOLOGS.getId(), false, argsIdentifier.NOLOGS.getDesc());
nologs.setOptionalArg(argsIdentifier.NOLOGS.getRequired());
cmdLineArgs.addOption(nologs);
Option verbose =
new Option(argsIdentifier.VERBOSE.getId(), false, argsIdentifier.VERBOSE.getDesc());
verbose.setOptionalArg(argsIdentifier.VERBOSE.getRequired());
cmdLineArgs.addOption(verbose);
Option vverbose =
new Option(argsIdentifier.VERYVERBOSE.getId(), false, argsIdentifier.VERYVERBOSE.getDesc());
vverbose.setOptionalArg(argsIdentifier.VERYVERBOSE.getRequired());
cmdLineArgs.addOption(vverbose);
Option newFile = new Option(argsIdentifier.NEW.getId(), false, argsIdentifier.NEW.getDesc());
newFile.setOptionalArg(argsIdentifier.NEW.getRequired());
cmdLineArgs.addOption(newFile);
//endregion
log.trace("Set the command line options to be used for parsing.");
return cmdLineArgs;
}
}
| 14,606 | 36.841969 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/EntryPoint.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface;
import static util.Utils.handleErrorMessage;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.argsIdentifier;
import java.util.ArrayList;
import org.apache.logging.log4j.Logger;
import util.Utils;
/**
* EntryPoint class.
*
* @author CryptoguardTeam Created on 12/5/18.
* @version 03.07.01
* @since 01.00.06
* <p>The main entry point of the program when this program is used via command-line and not as
* a library
*/
public class EntryPoint {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(EntryPoint.class);
/**
* main.
*
* @param args an array of {@link java.lang.String} objects.
*/
public static void main(String[] args) {
//Removing all of the empty string values, i.e. " "
ArrayList<String> strippedArgs = Utils.stripEmpty(args);
log.debug("Removed the empty arguments.");
boolean exitingJVM = !strippedArgs.contains(argsIdentifier.NOEXIT.getArg());
try {
//Fail Fast on the input validation
EnvironmentInformation generalInfo = ArgumentsCheck.paramaterCheck(strippedArgs);
System.out.println(SubRunner.run(generalInfo));
if (exitingJVM) System.exit(ExceptionId.SUCCESS.getId());
} catch (ExceptionHandler e) {
handleErrorMessage(e);
if (exitingJVM) System.exit(e.getErrorCode().getId());
}
}
}
| 1,544 | 27.611111 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/EntryPoint_Plugin.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface;
import static util.Utils.setDebuggingLevel;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.parameterChecks.Core;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.Listing;
import frontEnd.MessagingSystem.routing.outputStructures.common.Heuristics;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import rule.engine.EngineType;
import util.Utils;
/**
* EntryPoint_Plugin class.
*
* @author maister
* @version 03.10.00
*/
public class EntryPoint_Plugin {
/**
* main.
*
* @param sourceFiles a {@link java.util.List} object.
* @param dependencies a {@link java.util.List} object.
* @param outFile a {@link java.lang.String} object.
* @param mainFile a {@link java.lang.String} object.
* @param errorAddition a {@link java.util.function.Function} object.
* @param bugSummaryHandler a {@link java.util.function.Function} object.
* @param heuristicsHandler a {@link java.util.function.Function} object.
* @param debuggingLevel a int.
* @return a {@link java.lang.String} object.
* @param extraArgs a {@link java.util.List} object.
*/
public static String main(
List<String> sourceFiles,
List<String> dependencies,
String outFile,
String mainFile,
Function<AnalysisIssue, String> errorAddition,
Function<HashMap<Integer, Integer>, String> bugSummaryHandler,
Function<Heuristics, String> heuristicsHandler,
int debuggingLevel,
List<String> extraArgs) {
String outputFile = null;
//region Setting the logging level
setDebuggingLevel(debuggingLevel);
//endregion
try {
EnvironmentInformation info =
Core.paramaterCheck(
sourceFiles,
dependencies,
EngineType.CLASSFILES,
Listing.Default,
outFile,
mainFile,
extraArgs);
info.setErrorAddition(errorAddition);
info.setBugSummaryHandler(bugSummaryHandler);
info.setHeuristicsHandler(heuristicsHandler);
info.setPrettyPrint(true);
info.setKillJVM(false);
outputFile = SubRunner.run(info);
} catch (ExceptionHandler e) {
Utils.handleErrorMessage(e);
outputFile = e.toString();
}
return outputFile;
}
}
| 2,474 | 28.819277 | 75 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/SubRunner.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import org.apache.logging.log4j.Logger;
import rule.engine.*;
/**
* SubRunner class.
*
* @author maister
* @version 03.10.00
*/
public class SubRunner {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SubRunner.class);
/**
* run.
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
* @return a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static String run(EnvironmentInformation info) throws ExceptionHandler {
EntryHandler handler = null;
switch (info.getSourceType()) {
case APK:
log.debug("Chosen APK Scanning");
handler = new ApkEntry();
break;
case JAR:
log.debug("Chosen JAR Scanning");
handler = new JarEntry();
break;
case DIR:
log.debug("Chosen DIR Scanning");
handler = new SourceEntry();
break;
case JAVAFILES:
log.debug("Chosen JAVA FILE Scanning");
log.warn("This is still experimental, this has not stabilized yet.");
log.warn(
"Scanning Java Files is limited to Java 1.7 and lower, otherwise there may be issues.");
handler = new JavaFileEntry();
break;
case CLASSFILES:
log.debug("Chosen Java CLASS FILE Scanning");
handler = new JavaClassFileEntry();
break;
}
log.debug("Initializing the scanning process");
info.startScanning();
log.info("Starting the scanning process");
handler.Scan(info);
log.info("Stopped the scanning process");
info.stopScanning();
log.info("Writing the output to the file: " + info.getFileOut());
return info.getFileOut();
}
}
| 1,946 | 28.059701 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/Version.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import java.util.Arrays;
import org.apache.logging.log4j.Logger;
/**
* version handling class.
*
* @author franceme Created on 10/27/19.
* @version V03.07.06
* @since V03.07.06
* <p>The central point for handling the Java Version ().
*/
public enum Version {
//region Values
ONE(1, 45),
TWO(2, 46),
THREE(3, 47),
FOUR(4, 48),
FIVE(5, 49),
SIX(6, 50),
SEVEN(7, 51),
EIGHT(8, 52),
NINE(9, 53),
TEN(10, 54),
ELEVEN(11, 55),
TWELVE(12, 56),
THIRTEEN(13, 57),
FOURTEEN(14, 58),
FIFTEEN(15, 59),
SIXTEEN(16, 60),
SEVENTEEN(17, 61);
//endregion
//region Attributes
private int versionNumber;
private int majorVersion;
private static Version Supported = Version.EIGHT;
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(Version.class);
//endregion
//region Constructor
Version(int versionNumber, int majorVersion) {
this.versionNumber = versionNumber;
this.majorVersion = majorVersion;
}
//endregion
//region Methods
//region Overridden Methods
/** {@inheritDoc} */
@Override
public String toString() {
return String.valueOf(this.versionNumber);
}
//endregion
/**
* supported.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean supported() {
return this.majorVersion == Supported.majorVersion;
}
/**
* retrieveByMajor.
*
* @param majorVersion a int.
* @return a {@link frontEnd.Interface.Version} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static Version retrieveByMajor(int majorVersion) throws ExceptionHandler {
return Arrays.stream(Version.values())
.filter(v -> v.getMajorVersion() == majorVersion)
.findFirst()
.orElseThrow(
() ->
new ExceptionHandler(
"Major Version: " + majorVersion + " not valid.", ExceptionId.FILE_AFK));
}
/**
* getRunningVersion.
*
* @return a {@link frontEnd.Interface.Version} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static Version getRunningVersion() throws ExceptionHandler {
String version = System.getProperty("java.version");
log.debug("Java Version being used:" + version);
//Used for Java JRE versions below 9
if (version.startsWith("1.")) version = version.replaceFirst("1.", "");
//Getting the major number
int versionNumber = Integer.parseInt(version.substring(0, version.indexOf(".", 0)));
return Arrays.stream(Version.values())
.filter(v -> v.getVersionNumber() == versionNumber)
.findFirst()
.orElse(Version.ONE);
}
/**
* supportedByMajor.
*
* @param majorVersion a int.
* @return a boolean.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static boolean supportedByMajor(int majorVersion) throws ExceptionHandler {
return retrieveByMajor(majorVersion).getVersionNumber() <= Supported.majorVersion;
}
/**
* supportedFile.
*
* @return a boolean.
*/
public boolean supportedFile() {
return this.getVersionNumber() <= Supported.majorVersion;
}
/**
* Getter for the field <code>versionNumber</code>.
*
* @return a int.
*/
public int getVersionNumber() {
return this.versionNumber;
}
/**
* Getter for the field <code>majorVersion</code>.
*
* @return a int.
*/
public int getMajorVersion() {
return this.majorVersion;
}
//endregion
}
| 3,695 | 23.315789 | 93 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/formatArgument/Default.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.formatArgument;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import java.util.List;
import org.apache.commons.cli.Options;
/**
* Default class.
*
* @author franceme Created on 04/30/2019.
* @version 03.07.01
* @since 03.05.01
* <p>{Description Here}
*/
public class Default implements TypeSpecificArg {
/** Constructor for Default. */
public Default() {}
/** {@inheritDoc} The overridden method for the Legacy output. */
public Boolean inputValidation(EnvironmentInformation info, List<String> args) {
return true;
}
/**
* getOptions.
*
* @return a {@link org.apache.commons.cli.Options} object.
*/
public Options getOptions() {
return null;
}
}
| 772 | 21.735294 | 82 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/formatArgument/Legacy.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.formatArgument;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import java.util.List;
import org.apache.commons.cli.Options;
/**
* Legacy class.
*
* @author CryptoguardTeam Created on 12/13/18.
* @version 03.07.01
* @since 01.01.02
* <p>The input check for the Legacy Output
*/
public class Legacy implements TypeSpecificArg {
/** Constructor for Legacy. */
public Legacy() {}
/** {@inheritDoc} The overridden method for the Legacy output. */
public Boolean inputValidation(EnvironmentInformation info, List<String> args) {
return true;
}
/**
* getOptions.
*
* @return a {@link org.apache.commons.cli.Options} object.
*/
public Options getOptions() {
return null;
}
}
| 792 | 22.323529 | 82 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/formatArgument/ScarfXML.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.formatArgument;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.Listing;
import frontEnd.argsIdentifier;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.apache.commons.cli.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
/**
* ScarfXML class.
*
* @author CryptoguardTeam Created on 2018-12-14.
* @version 03.07.01
* @since 01.01.07
* <p>The Scarf Input check implementation.
*/
public class ScarfXML implements TypeSpecificArg {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ScarfXML.class);
/** Constructor for ScarfXML. */
public ScarfXML() {}
/** {@inheritDoc} The overridden method for the ScarfXML output. */
public Boolean inputValidation(EnvironmentInformation info, List<String> args)
throws ExceptionHandler {
CommandLine cmd = null;
Options cmdLineArgs = getOptions();
try {
cmd = new DefaultParser().parse(cmdLineArgs, args.stream().toArray(String[]::new));
} catch (ParseException e) {
String arg = null;
if (e.getMessage().startsWith("Missing required option: "))
arg =
argsIdentifier.lookup(e.getMessage().replace("Missing required option: ", "")).getArg();
if (arg == null) {
log.info("Retrieving help info");
throw new ExceptionHandler("Issue using arguments", ExceptionId.GEN_VALID);
} else {
log.fatal("Issue with the argument: " + arg);
throw new ExceptionHandler("Issue with the argument: " + arg, ExceptionId.GEN_VALID);
}
}
if (cmd.hasOption(argsIdentifier.SCONFIG.getId())) {
//region Retrieving and setting the values
Properties SWAMPProperties =
loadProperties(cmd.getOptionValue(argsIdentifier.SCONFIG.getId()));
info.setAssessmentFramework(SWAMPProperties.getProperty("assess_fw", "UNKNOWN"));
info.setAssessmentFrameworkVersion(
SWAMPProperties.getProperty("assess_fw_version", "UNKNOWN"));
info.setAssessmentStartTime(SWAMPProperties.getProperty("assessment_start_ts", null));
info.setBuildFramework(SWAMPProperties.getProperty("build_fw", "UNKNOWN"));
info.setBuildFrameworkVersion(SWAMPProperties.getProperty("build_fw_version", "UNKNOWN"));
info.setBuildRootDir(SWAMPProperties.getProperty("build_root_dir", "UNKNOWN"));
info.setPackageName(SWAMPProperties.getProperty("package_name", "UNKNOWN"));
info.setPackageRootDir(SWAMPProperties.getProperty("package_root_dir", "UNKNOWN"));
info.setPackageVersion(SWAMPProperties.getProperty("package_version", "UNKNOWN"));
info.setParserName(SWAMPProperties.getProperty("parser_fw", "UNKNOWN"));
info.setParserVersion(SWAMPProperties.getProperty("parser_fw_version", "UNKNOWN"));
info.setUUID(SWAMPProperties.getProperty("uuid", null));
//endregion
} else {
//region Setting the values if they're in the extra arguments list
info.setAssessmentFramework(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SASSESSFW.getId()), null));
info.setAssessmentFrameworkVersion(
cmd.getOptionValue(
StringUtils.trimToNull(argsIdentifier.SASSESSFWVERSION.getId()), null));
info.setAssessmentStartTime(
cmd.getOptionValue(
StringUtils.trimToNull(argsIdentifier.SASSESSMENTSTARTTS.getId()), null));
info.setBuildFramework(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SBUILDFW.getId()), null));
info.setBuildFrameworkVersion(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SBUILDFWVERSION.getId()), null));
info.setBuildRootDir(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SBUILDROOTDIR.getId()), null));
info.setPackageName(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SPACKAGENAME.getId()), null));
info.setPackageRootDir(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SPACKAGEROOTDIR.getId()), null));
info.setPackageVersion(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SPACKAGEVERSION.getId()), null));
info.setParserName(
cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SPARSERFW.getId()), null));
info.setParserVersion(
cmd.getOptionValue(
StringUtils.trimToNull(argsIdentifier.SPARSERFWVERSION.getId()), null));
info.setUUID(cmd.getOptionValue(StringUtils.trimToNull(argsIdentifier.SUUID.getId()), null));
//endregion
}
return true;
}
/**
* getOptions.
*
* @return a {@link org.apache.commons.cli.Options} object.
*/
public Options getOptions() {
Options cmdLineArgs = new Options();
for (argsIdentifier arg : Listing.ScarfXML.retrieveArgs()) {
Option tempConfig =
Option.builder(arg.getId())
.hasArg()
.argName(arg.getArgName())
.desc(arg.getDesc())
.build();
if (arg.hasDefaultArg()) tempConfig.setType(String.class);
tempConfig.setOptionalArg(arg.getRequired());
cmdLineArgs.addOption(tempConfig);
}
return cmdLineArgs;
}
/**
* loadProperties.
*
* @param path a {@link java.lang.String} object.
* @return a {@link java.util.Properties} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public Properties loadProperties(String path) throws ExceptionHandler {
try {
Properties SWAMPProperties = new Properties();
SWAMPProperties.load(new FileInputStream(path));
return SWAMPProperties;
} catch (FileNotFoundException e) {
log.fatal("Config File: " + path + " not found");
throw new ExceptionHandler("Config File: " + path + " not found", ExceptionId.FILE_AFK);
} catch (IOException e) {
log.fatal("Error Loading: " + path);
throw new ExceptionHandler("Error Loading: " + path, ExceptionId.FILE_READ);
}
}
}
| 6,323 | 39.538462 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/formatArgument/TypeSpecificArg.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.formatArgument;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import java.util.List;
import org.apache.commons.cli.Options;
/**
* TypeSpecificArg interface.
*
* @author CryptoguardTeam Created on 12/13/18.
* @version 03.07.01
* @since 01.01.02
* <p>The interface containing the commandline check for each messaging useage
*/
public interface TypeSpecificArg {
/**
* The interface for each type of routing to handle the raw command line arguments.
*
* @param info {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} - the continuation
* of the environmental info to be added onto.
* @param args String - The full set of arguments passed from the command line
* @return {@link java.lang.Boolean} - an indication if the validation passed.
* @throws ExceptionHandler - The main controlled exception.
*/
Boolean inputValidation(EnvironmentInformation info, List<String> args) throws ExceptionHandler;
/**
* getOptions.
*
* @return a {@link org.apache.commons.cli.Options} object.
*/
Options getOptions();
}
| 1,209 | 31.702703 | 99 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/outputRouting/ExceptionHandler.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.outputRouting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Supplier;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import util.Utils;
/**
* ExceptionHandler class.
*
* @author CryptoguardTeam Created on 2019-01-25.
* @version 03.07.01
* @since 02.00.03
* <p>The Main Exception Handling for the whole project
*/
public class ExceptionHandler extends Exception implements Supplier<String> {
private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(ExceptionHandler.class);
//region Attributes
private ExceptionId errorCode;
private ArrayList<String> longDesciption;
//endregion
//region Creations
/**
* Constructor for ExceptionHandler.
*
* @param message a {@link java.lang.String} object.
* @param id a {@link frontEnd.Interface.outputRouting.ExceptionId} object.
*/
public ExceptionHandler(String message, ExceptionId id) {
this(id, message);
//super(message);
}
/**
* Constructor for ExceptionHandler with multiple strings.
*
* @param id a {@link frontEnd.Interface.outputRouting.ExceptionId} object.
* @param message a {@link java.lang.String}... object.
*/
public ExceptionHandler(ExceptionId id, String... message) {
this.errorCode = id;
Arrays.stream(message).forEach(this.getLongDesciption()::add);
}
//endregion
//region Overridden Methods
/** {@inheritDoc} */
@Override
public String toString() {
String resp =
"==================================\n"
+ "Error ID: "
+ this.errorCode.getId()
+ "\n"
+ "Error Type: "
+ this.getLongDescriptionString()
+ "\n"
+ "Error Message: \n"
+ this.longDesciption
+ "\n"
+ "==================================";
return StringUtils.trimToNull(resp).concat("\n\n\n");
}
/** {@inheritDoc} */
@Override
public void printStackTrace() {
System.err.println(this.toString());
}
//endregion
//region Getters
/**
* Getter for the field <code>errorCode</code>.
*
* @return a {@link frontEnd.Interface.outputRouting.ExceptionId} object.
*/
public ExceptionId getErrorCode() {
return errorCode;
}
/**
* Getter for the field <code>longDesciption</code>.
*
* @return a {@link java.lang.String} object.
*/
public ArrayList<String> getLongDesciption() {
if (this.longDesciption == null) this.longDesciption = new ArrayList<>();
return longDesciption;
}
/**
* getLongDescriptionString.
*
* @return a {@link java.lang.String} object.
*/
public String getLongDescriptionString() {
return Utils.join("\n", this.getLongDesciption());
}
/** {@inheritDoc} */
@Override
public String get() {
return null;
}
//endregion
}
| 2,942 | 23.940678 | 77 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/outputRouting/ExceptionId.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.outputRouting;
/**
* ExceptionId class.
*
* @author CryptoguardTeam Created on 2/21/19.
* @version 03.07.01
* @since 03.02.11
* <p>The enumeration of the error codes.
*/
public enum ExceptionId {
//region Values
//region Range 0: Success
SUCCESS(0, "Successful"),
HELP(0, "Asking For Help"),
VERSION(0, "Asking For Version"),
//endregion
//region Range 1 -> 14 : Input Validation
GEN_VALID(1, "General Argument Validation"),
ARG_VALID(2, "Argument Value Validation"),
FORMAT_VALID(7, "Format Specific Argument Validation"),
//endregion
//region Range 15 -> 29 : File I
FILE_I(15, "File Input Error"),
FILE_READ(16, "Reading File Error"),
FILE_AFK(17, "File Not Available"),
//endregion
//region Range 30 -> 44 : File O
FILE_O(30, "File Output Error"),
FILE_CON(31, "Output File Creation Error"),
FILE_CUT(32, "Error Closing The File"),
//endregion
//region Range 45 -> 49 : Environment Variable
ENV_VAR(45, "Environment Variable Not Set"),
//endregion
//region Range 50 ->... -> 99 : TBD
//endregion
//region Range 100 -> 119 : Our Issue
MAR_VAR(100, "Error Marshalling The Output"),
//endregion
//region Range 120 -> 127 : Hail Mary
SCAN_GEN(120, "General Error Scanning The Program"),
LOADING(121, "Error Loading Class"),
UNKWN(127, "Unknown"),
//endregion
;
//endregion
//region Attributes
private Integer id;
private String message;
//endregion
//region constructor
ExceptionId(Integer id, String msg) {
this.id = id;
this.message = msg;
}
//endregion
//region Getter
/**
* Getter for the field <code>id</code>.
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getId() {
return id;
}
/**
* Getter for the field <code>message</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getMessage() {
return message;
}
//endregion
}
| 1,980 | 22.305882 | 57 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/outputRouting/parcelHandling.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.outputRouting;
import frontEnd.MessagingSystem.routing.Listing;
import frontEnd.argsIdentifier;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import util.Utils;
/**
* ExceptionId class.
*
* @author CryptoguardTeam Created on 04/25/19.
* @version 03.07.01
* @since 03.04.04
* <p>The enumeration of the error codes.
*/
public class parcelHandling {
private static final int Width = 140;
private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(parcelHandling.class);
/**
* retrieveHeaderInfo.
*
* @return a {@link java.lang.String} object.
*/
public static String retrieveHeaderInfo() {
return Utils.projectName + ": " + Utils.projectVersion + "\n";
}
/**
* getUsage.
*
* @return a {@link java.lang.String} object.
*/
public static String getUsage() {
StringBuilder output = new StringBuilder();
output.append("java -jar ").append(Utils.projectName.toLowerCase()).append(" ");
for (argsIdentifier arg : argsIdentifier.values())
if (arg.getFormatType() == null) {
output.append(arg.getArg()).append(" ");
if (arg.hasDefaultArg()) output.append("<").append(arg.getDefaultArg()).append("> ");
}
output.append("\n");
for (Listing type : Listing.values()) {
List<argsIdentifier> args = type.retrieveArgs();
if (args.size() > 1) {
output
.append("\n")
.append("FormatType ")
.append(type.getType())
.append(" specific arguments")
.append("\n");
output.append(StringUtils.repeat("#", Width / 4)).append("\n");
for (argsIdentifier arg : args) {
output.append(arg.getArg()).append(" ");
if (arg.hasDefaultArg()) output.append("<").append(arg.getDefaultArg()).append("> ");
}
output.append("\n");
}
}
return output.toString();
}
/**
* retrieveHelpFromOptions.
*
* @param args a {@link org.apache.commons.cli.Options} object.
* @param argIssue a {@link java.lang.String} object.
* @return a {@link java.lang.String} object.
*/
public static String retrieveHelpFromOptions(Options args, String argIssue) {
HelpFormatter helper = new HelpFormatter();
helper.setOptionComparator(null);
StringWriter message = new StringWriter();
PrintWriter redirect = new PrintWriter(message);
if (argIssue == null) message.append(StringUtils.repeat("#", Width)).append("\n");
message.append(retrieveHeaderInfo()).append("\n");
StringBuilder headerInfo = new StringBuilder();
headerInfo.append("\n");
if (argIssue == null) headerInfo.append("General Help");
else headerInfo.append(argIssue);
if (argIssue != null) {
headerInfo
.append(", please run java -jar ")
.append(Utils.projectName.toLowerCase())
.append(".jar -h for help.")
.append("\n")
.append(StringUtils.repeat("-", headerInfo.length()));
message.append(headerInfo);
} else {
helper.printHelp(redirect, Width, getUsage(), headerInfo.toString(), args, 0, 0, null);
for (Listing type : Listing.values()) {
try {
Options opt = type.retrieveSpecificArgHandler().getOptions();
if (opt != null) {
helper.printHelp(
redirect, Width, type.getType() + " specific usage", null, opt, 0, 0, null);
}
} catch (ExceptionHandler e) {
log.warn("Issue retrieving arguments from " + type.getType() + " listing type");
}
}
message.append(StringUtils.repeat("#", Width)).append("\n");
}
return message.toString();
}
}
| 3,941 | 29.796875 | 95 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/parameterChecks/Container.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.parameterChecks;
import static util.Utils.prep;
import frontEnd.Interface.SubRunner;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.Listing;
import frontEnd.argsIdentifier;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import rule.engine.EngineType;
import util.Utils;
/**
* @author franceme Created on 2020-11-16.
* @since 04.05.02
* <p>Container
* <p>The "Builder Class" to interface with CryptoGuard This class allows developers to
* integrate more freely with the internals with a builder pattern type of approach.
*/
public class Container {
//region Attributes
private String javaHome = null;
private String androidHome = null;
private Integer debuggingLevel = -1;
private Listing listing = Listing.Default;
private EngineType engineType = EngineType.CLASSFILES;
private List<String> sourceValues = new ArrayList<String>();
private List<String> dependencyValues = new ArrayList<String>();
private Boolean overwriteOutFile = false;
private String outFile = null;
private String mainFile = null;
private Boolean prettyPrint = true;
private Boolean showTimes = false;
private Boolean streaming = true;
private Boolean displayHeuristics = false;
private Integer scanningDepth = null;
private String packageName = null;
//endregion
//region Constructors
public Container() {}
//endregion
//region Getters Setters
public EngineType getEngineType() {
return engineType;
}
public void setEngineType(EngineType engineType) {
this.engineType = engineType;
}
public String getJavaHome() {
return javaHome;
}
public void setJavaHome(String javaHome) {
this.javaHome = javaHome;
}
public String getAndroidHome() {
return androidHome;
}
public void setAndroidHome(String androidHome) {
this.androidHome = androidHome;
}
public Integer getDebuggingLevel() {
return debuggingLevel;
}
public void setDebuggingLevel(Integer debuggingLevel) {
this.debuggingLevel = debuggingLevel;
}
public Listing getListing() {
return listing;
}
public void setListing(Listing listing) {
this.listing = listing;
}
public List<String> getSourceValues() {
return sourceValues;
}
public void setSourceValues(List<String> sourceValues) {
this.sourceValues = sourceValues;
}
public List<String> getDependencyValues() {
return dependencyValues;
}
public void setDependencyValues(List<String> dependencyValues) {
this.dependencyValues = dependencyValues;
}
public Boolean getOverwriteOutFile() {
return overwriteOutFile;
}
public void setOverwriteOutFile(Boolean overwriteOutFile) {
this.overwriteOutFile = overwriteOutFile;
}
public String getOutFile() {
return outFile;
}
public void setOutFile(String outFile) {
this.outFile = outFile;
}
public String getMainFile() {
return mainFile;
}
public void setMainFile(String mainFile) {
this.mainFile = mainFile;
}
public Boolean getPrettyPrint() {
return prettyPrint;
}
public void setPrettyPrint(Boolean prettyPrint) {
this.prettyPrint = prettyPrint;
}
public Boolean getShowTimes() {
return showTimes;
}
public void setShowTimes(Boolean showTimes) {
this.showTimes = showTimes;
}
public Boolean getStreaming() {
return streaming;
}
public void setStreaming(Boolean streaming) {
this.streaming = streaming;
}
public Boolean getDisplayHeuristics() {
return displayHeuristics;
}
public void setDisplayHeuristics(Boolean displayHeuristics) {
this.displayHeuristics = displayHeuristics;
}
public Integer getScanningDepth() {
return scanningDepth;
}
public void setScanningDepth(Integer scanningDepth) {
this.scanningDepth = scanningDepth;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
//endregion
//region Builder Methods
public Container addSourceValue(String sourceValue) {
this.sourceValues.add(sourceValue);
return this;
}
public Container addSourceValues(List<String> sourceValues) {
this.sourceValues.addAll(sourceValues);
return this;
}
public Container addDependencyValue(String dependencyValue) {
this.dependencyValues.add(dependencyValue);
return this;
}
public Container addDependencyValue(List<String> dependencyValues) {
this.dependencyValues.addAll(sourceValues);
return this;
}
public Container withEngineType(EngineType engineType) {
this.engineType = engineType;
return this;
}
public Container withJavaHome(String javaHome) {
this.javaHome = javaHome;
return this;
}
public Container withAndroidHome(String androidHome) {
this.androidHome = androidHome;
return this;
}
public Container withDebuggingLevel(Integer debuggingLevel) {
this.debuggingLevel = debuggingLevel;
return this;
}
public Container withFormatLevel(Listing formatLevel) {
this.listing = formatLevel;
return this;
}
public Container withSourceValues(List<String> sourceValues) {
this.sourceValues = sourceValues;
return this;
}
public Container withDependencyValues(List<String> dependencyValues) {
this.dependencyValues = dependencyValues;
return this;
}
public Container withOverwriteOutFile(Boolean overwriteOutFile) {
this.overwriteOutFile = overwriteOutFile;
return this;
}
public Container withOutFile(String outFile) {
this.outFile = outFile;
return this;
}
public Container withMainFile(String mainFile) {
this.mainFile = mainFile;
return this;
}
public Container withPrettyPrint(Boolean prettyPrint) {
this.prettyPrint = prettyPrint;
return this;
}
public Container withShowTimes(Boolean showTimes) {
this.showTimes = showTimes;
return this;
}
public Container withStreaming(Boolean streaming) {
this.streaming = streaming;
return this;
}
public Container withDisplayHeuristics(Boolean displayHeuristics) {
this.displayHeuristics = displayHeuristics;
return this;
}
public Container withScanningDepth(Integer scanningDepth) {
this.scanningDepth = scanningDepth;
return this;
}
public Container withPackageName(String packageName) {
this.packageName = packageName;
return this;
}
//endregion
//region Methods
public String build() throws ExceptionHandler {
setDebuggingLevel(this.getDebuggingLevel());
EnvironmentInformation info =
Core.paramaterCheck(
this.getSourceValues(),
this.getDependencyValues(),
this.getEngineType(),
this.getListing(),
this.getOutFile(),
this.getOverwriteOutFile(),
this.getMainFile(),
this.getShowTimes(),
this.getJavaHome(),
this.getAndroidHome(),
null);
info.setPrettyPrint(this.getPrettyPrint());
info.setShowTimes(this.getShowTimes());
info.setStreaming(this.getStreaming());
info.setDisplayHeuristics(this.getDisplayHeuristics());
info.setPackageName(this.getPackageName());
info.setKillJVM(false);
Utils.initDepth(this.getScanningDepth());
info.setRawCommand(
Utils.makeArg(argsIdentifier.SOURCE, this.getSourceValues())
+ Utils.makeArg(argsIdentifier.DEPENDENCY, this.getDependencyValues())
+ Utils.makeArg(argsIdentifier.FORMAT, this.getEngineType())
+ Utils.makeArg(argsIdentifier.FORMATOUT, this.getListing())
+ Utils.makeArg(argsIdentifier.OUT, this.getOutFile())
+ Utils.makeArg(argsIdentifier.NEW, this.getOverwriteOutFile())
+ (StringUtils.isNotEmpty(this.getMainFile())
? Utils.makeArg(argsIdentifier.MAIN, this.getMainFile())
: "")
+ Utils.makeArg(argsIdentifier.TIMESTAMP, this.getShowTimes())
+ Utils.makeArg(argsIdentifier.STREAM, this.getStreaming())
+ Utils.makeArg(argsIdentifier.HEURISTICS, this.getDisplayHeuristics())
+ Utils.makeArg(argsIdentifier.DEPTH, this.getScanningDepth())
+ Utils.makeArg(argsIdentifier.JAVA, this.getJavaHome())
+ Utils.makeArg(argsIdentifier.ANDROID, this.getAndroidHome())
+ Utils.makeArg(argsIdentifier.VERBOSE, this.getDebuggingLevel())
+ Utils.makeArg(argsIdentifier.PRETTY, this.getPrettyPrint())
+ Utils.makeArg(argsIdentifier.JAVA, this.getJavaHome()));
return SubRunner.run(info);
}
@Override
public String toString() {
return "\"Container\": {"
+ "\"javaHome\":"
+ prep(this.getJavaHome())
+ ","
+ "\"androidHome\":"
+ prep(this.getAndroidHome())
+ ","
+ "\"debuggingLevel\":"
+ prep(this.getDebuggingLevel())
+ ","
+ "\"listing\":"
+ prep(this.getListing())
+ ","
+ "\"engineType\":"
+ prep(this.getEngineType())
+ ","
+ "\"sourceValues\":"
+ prep(this.getSourceValues())
+ ","
+ "\"dependencyValues\":"
+ prep(this.getDependencyValues())
+ ","
+ "\"overwriteOutFile\":"
+ prep(this.getOverwriteOutFile())
+ ","
+ "\"outFile\":"
+ prep(this.getOutFile())
+ ","
+ "\"mainFile\":"
+ prep(this.getMainFile())
+ ","
+ "\"prettyPrint\":"
+ prep(this.getPrettyPrint())
+ ","
+ "\"showTimes\":"
+ prep(this.getShowTimes())
+ ","
+ "\"streaming\":"
+ prep(this.getStreaming())
+ ","
+ "\"displayHeuristics\":"
+ prep(this.getDisplayHeuristics())
+ ","
+ "\"scanningDepth\":"
+ prep(this.getScanningDepth())
+ ","
+ "\"packageName\":"
+ prep(this.getPackageName())
+ "}";
}
//endregion
}
| 10,220 | 25.548052 | 91 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/Interface/parameterChecks/Core.java | /* Licensed under GPL-3.0 */
package frontEnd.Interface.parameterChecks;
import static util.Utils.retrieveFullyQualifiedName;
import frontEnd.Interface.Version;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.Listing;
import frontEnd.argsIdentifier;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import rule.engine.EngineType;
import util.Utils;
/**
* @author franceme Created on 2020-11-16.
* @since 04.05.02
* <p>Core
* <p>The utility class containing the specific Parameter Check Routing
*/
public class Core {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(Core.class);
//region Methods
/**
* paramaterCheck.
*
* @param sourceFiles a {@link java.util.List} object.
* @param dependencies a {@link java.util.List} object.
* @param eType a {@link rule.engine.EngineType} object.
* @param oType a {@link frontEnd.MessagingSystem.routing.Listing} object.
* @param fileOutPath a {@link java.lang.String} object.
* @param mainFile a {@link java.lang.String} object.
* @param extraArguments a {@link java.util.List} object.
* @return a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static EnvironmentInformation paramaterCheck(
List<String> sourceFiles,
List<String> dependencies,
EngineType eType,
Listing oType,
String fileOutPath,
String mainFile,
List<String> extraArguments)
throws ExceptionHandler {
EnvironmentInformation info =
paramaterCheck(
sourceFiles,
dependencies,
eType,
oType,
fileOutPath,
true,
StringUtils.trimToNull(mainFile),
false,
null,
null,
extraArguments);
//Setting base arguments, some might turn into defaults
info.setShowTimes(true);
info.setStreaming(true);
info.setDisplayHeuristics(true);
Utils.initDepth(1);
info.setRawCommand(
Utils.makeArg(argsIdentifier.SOURCE, info.getSource())
+ Utils.makeArg(argsIdentifier.DEPENDENCY, info.getDependencies())
+ Utils.makeArg(argsIdentifier.FORMAT, eType)
+ Utils.makeArg(argsIdentifier.FORMATOUT, oType)
+ Utils.makeArg(argsIdentifier.OUT, info.getFileOut())
+ Utils.makeArg(argsIdentifier.NEW, true)
+ (StringUtils.isNotEmpty(mainFile)
? Utils.makeArg(argsIdentifier.MAIN, info.getMain())
: "")
+ Utils.makeArg(argsIdentifier.TIMESTAMP, false)
+ Utils.makeArg(argsIdentifier.TIMEMEASURE, true)
+ Utils.makeArg(argsIdentifier.STREAM, true)
+ Utils.makeArg(argsIdentifier.HEURISTICS, true)
+ Utils.makeArg(argsIdentifier.DEPTH, 1)
+ Utils.join(" ", extraArguments));
return info;
}
/**
* paramaterCheck.
*
* @param sourceFiles a {@link java.util.List} object.
* @param dependencies a {@link java.util.List} object.
* @param eType a {@link rule.engine.EngineType} object.
* @param oType a {@link frontEnd.MessagingSystem.routing.Listing} object.
* @param fileOutPath a {@link java.lang.String} object.
* @param overWriteFileOut a {@link java.lang.Boolean} object.
* @param mainFile a {@link java.lang.String} object.
* @param timeStamp a {@link java.lang.Boolean} object.
* @param java a {@link java.lang.String} object.
* @param android a {@link java.lang.String} object.
* @return a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
* @param extraArguments a {@link java.util.List} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public static EnvironmentInformation paramaterCheck(
List<String> sourceFiles,
List<String> dependencies,
EngineType eType,
Listing oType,
String fileOutPath,
Boolean overWriteFileOut,
String mainFile,
Boolean timeStamp,
String java,
String android,
List<String> extraArguments)
throws ExceptionHandler {
//region verifying current running version
Version currentVersion = Version.getRunningVersion();
if (StringUtils.isBlank(java) && !currentVersion.supported()) {
log.fatal("JRE Version: " + currentVersion + " is not compatible");
throw new ExceptionHandler(
"JRE Version: "
+ currentVersion
+ " is not compatible, please use JRE Version: "
+ Version.EIGHT,
ExceptionId.GEN_VALID);
}
//endregion
//region verifying filePaths
//region Setting the source files
log.trace("Retrieving the source files.");
ArrayList<String> vSources =
(sourceFiles.size() == 1 && sourceFiles.get(0).equals("xargs"))
? Utils.retrievingThroughXArgs(eType, false, true)
: Utils.retrieveFilePathTypes(new ArrayList<>(sourceFiles), eType, true, false, true);
log.info("Scanning " + retrieveFullyQualifiedName(vSources).size() + " source file(s).");
log.debug("Using the source file(s): " + retrieveFullyQualifiedName(vSources).toString());
//endregion
//region Setting the dependency path
log.trace("Retrieving the dependency files.");
List<String> vDeps =
Utils.retrieveFilePathTypes(new ArrayList<>(dependencies), false, false, false);
if (vDeps.size() > 0)
log.debug("Using the dependency file(s) :" + retrieveFullyQualifiedName(vDeps).toString());
//endregion
//endregion
//region Retrieving the package path
log.trace("Retrieving the package path, may/may not be able to be replaced.");
List<String> basePath = new ArrayList<>();
File sourceFile;
String pkg = "";
switch (eType) {
case APK:
case JAR:
sourceFile = new File(sourceFiles.get(0));
basePath.add(sourceFile.getName());
pkg = sourceFile.getName();
break;
case DIR:
sourceFile = new File(sourceFiles.get(0));
try {
basePath.add(sourceFile.getCanonicalPath() + ":dir");
} catch (IOException e) {
}
pkg = sourceFile.getName();
break;
case JAVAFILES:
case CLASSFILES:
for (String file : sourceFiles) {
try {
sourceFile = new File(file);
basePath.add(sourceFile.getCanonicalPath());
if (pkg == null) {
pkg = sourceFile.getCanonicalPath();
}
} catch (IOException e) {
}
}
break;
}
log.debug("Package path: " + pkg);
//endregion
EnvironmentInformation info =
new EnvironmentInformation(vSources, eType, oType, vDeps, basePath, pkg);
info.setJavaHome(java);
info.setAndroidHome(android);
//Verifying the right argument is set based on the Enginetype
info.verifyBaseSettings();
if (StringUtils.isNotEmpty(mainFile)) {
log.info("Attempting to validate the main method as " + mainFile);
if (!info.getSource().contains(mainFile)) {
log.fatal("The main class path is not included within the source file.");
throw new ExceptionHandler(
"The main class path is not included within the source file.", ExceptionId.ARG_VALID);
}
log.info("Using the main method from class " + mainFile);
info.setMain(mainFile);
}
//region Setting the file out
if (fileOutPath == null) {
fileOutPath =
Utils.getDefaultFileOut(
info.getPackageName(), info.getMessagingType().getOutputFileExt());
} else {
String ogFileOutPath = fileOutPath;
fileOutPath =
Utils.retrieveFilePath(
fileOutPath, oType.getOutputFileExt(), overWriteFileOut, true, false);
if (fileOutPath == null) {
log.warn("Output file: " + ogFileOutPath + " is not available.");
fileOutPath =
Utils.getDefaultFileOut(
info.getPackageName(), info.getMessagingType().getOutputFileExt());
log.warn("Defaulting the output to file: " + fileOutPath);
}
}
info.setFileOut(fileOutPath);
//endregion
//region Specific Parameter Checking
if (extraArguments != null && extraArguments.size() > 1)
oType.retrieveSpecificArgHandler().inputValidation(info, extraArguments);
//endregion
return info;
}
//endregion
}
| 8,813 | 34.540323 | 98 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/AnalysisIssue.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem;
import analyzer.backward.UnitContainer;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import rule.engine.RuleList;
import util.Utils;
/**
* The class containing the specific analysis issue information. The "flat" structure to be
* transformed to various formats.
*
* <p>STATUS: IC
*
* @author franceme
* @version 03.07.01
* @since V01.00.01
*/
public class AnalysisIssue {
//region Attributes
private String fullPathName;
private String className;
private RuleList rule;
private Stack methods;
private ArrayList<AnalysisLocation> locations;
private String info;
//endregion
//region Constructors
/**
* Constructor for AnalysisIssue.
*
* @param ruleNumber a {@link java.lang.Integer} object.
*/
public AnalysisIssue(Integer ruleNumber) {
this.rule = RuleList.getRuleByRuleNumber(ruleNumber);
}
/**
* Constructor for AnalysisIssue.
*
* @param sootString a {@link java.lang.String} object.
* @param ruleNumber a {@link java.lang.Integer} object.
* @param Info a {@link java.lang.String} object.
* @param sourcePaths a {@link java.util.List} object.
*/
public AnalysisIssue(
String sootString, Integer ruleNumber, String Info, List<String> sourcePaths) {
String className = Utils.retrieveClassNameFromSootString(sootString);
String methodName = Utils.retrieveMethodFromSootString(sootString);
Integer lineNum = Utils.retrieveLineNumFromSootString(sootString);
String constant = null;
if (sootString.contains("constant keys") || ruleNumber == 3)
constant = Utils.retrieveFoundMatchFromSootString(sootString);
if (lineNum >= 0) this.addMethod(methodName, new AnalysisLocation(lineNum));
else this.addMethod(methodName);
this.className = className;
this.rule = RuleList.getRuleByRuleNumber(ruleNumber);
if (constant != null) Info += " Found value \"" + constant + "\"";
this.info = Info;
this.fullPathName = getPathFromSource(sourcePaths, className);
}
/**
* Constructor for AnalysisIssue.
*
* @param unit a {@link analyzer.backward.UnitContainer} object.
* @param ruleNumber a {@link java.lang.Integer} object.
* @param sootString a {@link java.lang.String} object.
* @param sourcePaths a {@link java.util.List} object.
*/
public AnalysisIssue(
UnitContainer unit, Integer ruleNumber, String sootString, List<String> sourcePaths) {
Integer lineNum;
String constant = null;
if (sootString.contains("constant keys") || ruleNumber == 3)
constant = Utils.retrieveFoundMatchFromSootString(sootString);
String methodName = Utils.retrieveMethodFromSootString(unit.getMethod());
if ((lineNum = unit.getUnit().getJavaSourceStartLineNumber()) >= 0) {
AnalysisLocation tempLoc = new AnalysisLocation(lineNum);
if (unit.getUnit().getJavaSourceStartColumnNumber() >= 0) {
tempLoc.setColStart(unit.getUnit().getJavaSourceStartColumnNumber());
tempLoc.setColEnd(unit.getUnit().getJavaSourceStartColumnNumber());
}
this.addMethod(methodName, tempLoc);
}
this.className = Utils.retrieveClassNameFromSootString(unit.getMethod());
this.rule = RuleList.getRuleByRuleNumber(ruleNumber);
this.info = Utils.retrieveFoundPatternFromSootString(sootString);
if (this.info.equals("UNKNOWN") && constant != null)
this.info = "Found: Constant \"" + constant + "\"";
else if (this.info.equals("UNKNOWN") && constant == null) this.info = "Found: " + sootString;
else if (constant != null) this.info += " Found value \"" + constant + "\"";
else this.info = "Found: \"" + this.info + "\"";
this.info = this.info.replace("Found: Found: ", "Found: ");
if (lineNum <= 0) {
this.addMethod(
methodName, new AnalysisLocation(Utils.retrieveLineNumFromSootString(sootString)));
}
if (this.getMethods().empty()) this.addMethod(methodName);
this.fullPathName = getPathFromSource(sourcePaths, className);
}
//endregion
//region Helper Methods
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder out = new StringBuilder();
out.append("ClassName: ").append(this.className).append(", ");
out.append("Rule: ").append(this.rule).append(", ");
out.append("Methods: ").append(this.methods.peek().toString()).append(", ");
if (getLocations().size() > 0) {
out.append("Locations: ");
getLocations().stream().forEach(loc -> out.append(loc.toString()).append(" && "));
} else out.append("No Locations");
out.append(", ");
out.append("Info: ").append(this.info);
return out.toString();
}
/**
* getPathFromSource.
*
* @param sources a {@link java.util.List} object.
* @param className a {@link java.lang.String} object.
* @return a {@link java.lang.String} object.
*/
public String getPathFromSource(List<String> sources, String className) {
String relativePath = null;
if (sources.size() == 1) {
String fullSource = sources.get(0);
String[] split = fullSource.split(Utils.fileSep);
fullSource = split[split.length - 1];
if (fullSource.endsWith(":dir"))
relativePath =
Utils.osPathJoin(
fullSource.replace(":dir", ""),
"src",
"main",
"java",
className.replace(".", System.getProperty("file.separator")) + ".java");
else
relativePath =
Utils.osPathJoin(
fullSource,
className.replace(".", System.getProperty("file.separator")) + ".class");
} else {
for (String in : sources)
if (in.contains(className)) {
//String[] split = in.split(Utils.fileSep);
//relativePath = split[split.length - 1];
relativePath = in;
} else if (in.contains(className.replace(".", Utils.fileSep))) {
//String[] split = in.split(Utils.fileSep);
//relativePath = split[split.length - 1];
relativePath = in;
}
}
if (relativePath == null) return "UNKNOWN";
else return relativePath;
}
//endregion
//region Getters/Setters
/**
* Getter for the field <code>fullPathName</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getFullPathName() {
return fullPathName;
}
/**
* Setter for the field <code>fullPathName</code>.
*
* @param fullPathName a {@link java.lang.String} object.
*/
public void setFullPathName(String fullPathName) {
this.fullPathName = fullPathName;
}
/**
* Getter for the field <code>className</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getClassName() {
return className;
}
/**
* Setter for the field <code>className</code>.
*
* @param className a {@link java.lang.String} object.
*/
public void setClassName(String className) {
this.className = className;
}
/**
* Getter for the field <code>rule</code>.
*
* @return a {@link rule.engine.RuleList} object.
*/
public RuleList getRule() {
return rule;
}
/**
* getRuleId.
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getRuleId() {
return rule.getRuleId();
}
/**
* Getter for the field <code>methods</code>.
*
* @return a {@link java.util.Stack} object.
*/
public Stack getMethods() {
if (this.methods == null) {
this.methods = new Stack();
}
return this.methods;
}
/**
* Getter for the field <code>locations</code>.
*
* @return a {@link java.util.ArrayList} object.
*/
public ArrayList<AnalysisLocation> getLocations() {
if (this.locations == null) {
this.locations = new ArrayList<>();
}
return locations;
}
/**
* addLocation.
*
* @param newLocation a {@link frontEnd.MessagingSystem.AnalysisLocation} object.
*/
public void addLocation(AnalysisLocation newLocation) {
this.getLocations().add(newLocation);
}
/**
* addMethod.
*
* @param methodName a {@link java.lang.String} object.
*/
public void addMethod(String methodName) {
this.getMethods().push(String.valueOf(methodName));
}
/**
* addMethod.
*
* @param methodName a {@link java.lang.String} object.
* @param location a {@link frontEnd.MessagingSystem.AnalysisLocation} object.
*/
public void addMethod(String methodName, AnalysisLocation location) {
location.setMethodNumber(this.getMethods().size());
this.getMethods().push(String.valueOf(methodName));
this.addLocation(location);
}
/**
* Getter for the field <code>info</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getInfo() {
return info;
}
/**
* Setter for the field <code>info</code>.
*
* @param info a {@link java.lang.String} object.
*/
public void setInfo(String info) {
this.info = info;
}
//endregion
}
| 9,070 | 26.910769 | 97 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/AnalysisLocation.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem;
/**
* AnalysisLocation class.
*
* @author franceme
* @version 03.07.01
* @since V01.00.00
*/
public class AnalysisLocation {
//region Attributes
private Integer lineStart = null;
private Integer lineEnd = null;
private Integer colStart = null;
private Integer colEnd = null;
private Integer methodNumber = -1;
//endregion
//region Constructor
/**
* Constructor for AnalysisLocation.
*
* @param start a {@link java.lang.Integer} object.
* @param end a {@link java.lang.Integer} object.
*/
public AnalysisLocation(Integer start, Integer end) {
this.lineStart = start;
this.lineEnd = end;
}
/**
* Constructor for AnalysisLocation.
*
* @param lineNumber a {@link java.lang.Integer} object.
*/
public AnalysisLocation(Integer lineNumber) {
this.lineStart = lineNumber;
this.lineEnd = lineNumber;
}
/**
* Constructor for AnalysisLocation.
*
* @param start a {@link java.lang.Integer} object.
* @param end a {@link java.lang.Integer} object.
* @param methodNumber a {@link java.lang.Integer} object.
*/
public AnalysisLocation(Integer start, Integer end, Integer methodNumber) {
this.lineStart = start;
this.lineEnd = end;
this.methodNumber = methodNumber;
}
//endregion
//region Overridden Methods
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder output = new StringBuilder();
output.append(this.lineStart);
if (!this.lineEnd.equals(this.lineStart)) {
output.append("-");
output.append(this.lineEnd);
}
return output.toString();
}
//endregion
//region Getters
/**
* Getter for the field <code>lineStart</code>.
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getLineStart() {
return lineStart;
}
/**
* Getter for the field <code>lineEnd</code>.
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getLineEnd() {
return lineEnd;
}
/**
* Getter for the field <code>methodNumber</code>.
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getMethodNumber() {
return methodNumber;
}
/**
* Setter for the field <code>methodNumber</code>.
*
* @param methodNumber a {@link java.lang.Integer} object.
*/
public void setMethodNumber(Integer methodNumber) {
this.methodNumber = methodNumber;
}
/**
* Getter for colStart
*
* <p>getColStart()
*
* @return {@link java.lang.Integer} - The colStart.
*/
public Integer getColStart() {
return colStart;
}
/**
* Setter for colStart
*
* <p>setColStart(java.lang.Integer colStart)
*
* @param colStart {@link java.lang.Integer} - The value to set as colStart
*/
public void setColStart(Integer colStart) {
this.colStart = colStart;
}
/**
* Getter for colEnd
*
* <p>getColEnd()
*
* @return {@link java.lang.Integer} - The colEnd.
*/
public Integer getColEnd() {
return colEnd;
}
/**
* Setter for colEnd
*
* <p>setColEnd(java.lang.Integer colEnd)
*
* @param colEnd {@link java.lang.Integer} - The value to set as colEnd
*/
public void setColEnd(Integer colEnd) {
this.colEnd = colEnd;
}
//endregion
}
| 3,338 | 19.86875 | 77 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/EnvironmentInformation.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.outputStructures.OutputStructure;
import frontEnd.MessagingSystem.routing.outputStructures.common.Heuristics;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import rule.engine.EngineType;
import soot.G;
import util.Utils;
/**
* The class containing the analysis rule information.
*
* <p>STATUS: IC
*
* @author franceme
* @version 03.07.01
* @since V01.00.04
*/
public class EnvironmentInformation {
private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(EnvironmentInformation.class);
//region Attributes
//region Self Generated
private final Properties Properties = new Properties();
private final String PropertiesFile = "gradle.properties";
private String ToolFramework;
private String ToolFrameworkVersion;
private String platformName = Utils.getPlatform();
//endregion
//region Required Elements Set From the Start
private final List<String> Source;
private final List<String> sourcePaths; //Could this be intertwined with source?
//endregion
PrintStream old;
private String BuildFramework;
private String BuildFrameworkVersion;
private String packageName = "UNKNOWN";
private String packageVersion = "UNKNOWN";
private boolean showTimes = false;
private boolean addExperimentalRules = false;
private String rawCommand;
private String main;
private boolean overWriteOutput = false;
private String targetProjectName;
private String targetProjectVersion;
private Boolean isGradle;
private Boolean prettyPrint = false;
private Boolean killJVM = true;
private List<String> dependencies;
private EngineType sourceType;
private Listing messagingType;
private String UUID;
private Long startAnalyisisTime;
private Long analysisMilliSeconds;
private String fileOut;
private Boolean streaming = false;
String javaHome;
String androidHome;
//region From Outside and defaulted unless set
private String AssessmentFramework;
private String AssessmentFrameworkVersion;
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss");
private LocalDateTime startTime = LocalDateTime.now();
private String AssessmentStartTime = startTime.format(formatter);
private String ParserName = "UNKNOWN";
private String ParserVersion = "UNKNOWN";
private String packageRootDir = "UNKNOWN";
private String buildRootDir = "UNKNOWN";
private Integer buildId;
private String xPath;
private Boolean printOut = false;
private OutputStructure output;
//endregion
private ByteArrayOutputStream sootErrors = new ByteArrayOutputStream();
//region Heuristics from Utils
private Boolean displayHeuristics = false;
private Heuristics heuristics = new Heuristics();
//endregion
//region Predicates used to help display streamed info
private Function<AnalysisIssue, String> errorAddition;
private Function<HashMap<Integer, Integer>, String> bugSummaryHandler;
private Function<Heuristics, String> heuristicsHandler;
//endregion
//endregion
//region Constructor
/** Constructor for EnvironmentInformation. */
public EnvironmentInformation() {
this.ToolFramework = "";
this.ToolFrameworkVersion = "";
this.sourcePaths = new ArrayList<>();
this.Source = new ArrayList<>();
}
/**
* The main constructor for setting all of the environmental variables used for the outputs.
*
* @param source a {@link java.util.List} object.
* @param sourceType a {@link rule.engine.EngineType} object.
* @param messagingType a {@link frontEnd.MessagingSystem.routing.Listing} object.
* @param dependencies a {@link java.util.List} object.
* @param sourcePaths a {@link java.util.List} object.
* @param sourcePkg a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public EnvironmentInformation(
@Nonnull List<String> source,
@Nonnull EngineType sourceType,
Listing messagingType,
List<String> dependencies,
List<String> sourcePaths,
String sourcePkg)
throws ExceptionHandler {
//region Setting Internal Version Settings
String tempToolFrameworkVersion;
String tempToolFramework;
try {
Properties.load(new FileInputStream(PropertiesFile));
tempToolFrameworkVersion = Properties.getProperty("versionNumber");
tempToolFramework = Properties.getProperty("projectName");
} catch (FileNotFoundException e) {
tempToolFrameworkVersion = "Property Not Found";
tempToolFramework = "Property Not Found";
} catch (IOException e) {
tempToolFrameworkVersion = "Not Available";
tempToolFramework = "Not Available";
}
ToolFrameworkVersion = tempToolFrameworkVersion;
ToolFramework = tempToolFramework;
//endregion
//region Setting Required Attributes
//Redirecting the Soot Output - might need to change this
G.v().out = new PrintStream(this.sootErrors);
this.Source = source;
this.sourceType = sourceType;
if (dependencies != null) this.dependencies = dependencies;
this.messagingType = messagingType;
this.sourcePaths = sourcePaths;
String[] pkgs = sourcePkg.split(System.getProperty("file.separator"));
this.packageName = pkgs[pkgs.length - 1].split("\\.")[0];
//this.setPackageRootDir(sourcePkg);
//this.setBuildRootDir(sourcePkg);
this.setPackageRootDir();
this.setBuildRootDir();
//endregion
}
//endregion
//region Getters and Setters
/**
* verifyBaseSettings.
*
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void verifyBaseSettings() throws ExceptionHandler {
switch (this.sourceType) {
case DIR:
case JAVAFILES:
if (StringUtils.isEmpty(getJavaHome())) {
log.fatal("Please set JAVA7_HOME or specify via the arguments.");
throw new ExceptionHandler(
"Please set JAVA7_HOME or specify via the arguments.", ExceptionId.ENV_VAR);
}
break;
case APK:
if (StringUtils.isEmpty(getAndroidHome())) {
log.fatal("Please set ANDROID_HOME or specify via the arguments.");
throw new ExceptionHandler(
"Please set ANDROID_HOME or specify via the arguments.", ExceptionId.ENV_VAR);
}
case JAR:
case CLASSFILES:
if (StringUtils.isEmpty(getJavaHome())) {
log.fatal("Please set JAVA_HOME or specify via the arguments.");
throw new ExceptionHandler(
"Please set JAVA_HOME or specify via the arguments.", ExceptionId.ENV_VAR);
}
break;
}
}
/**
* Getter for the field <code>androidHome</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getAndroidHome() {
if (StringUtils.isEmpty(this.androidHome))
this.androidHome = System.getenv("ANDROID_HOME").replaceAll("//", "/");
return this.androidHome;
}
/**
* Getter for the field <code>javaHome</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getJavaHome() {
if (StringUtils.isEmpty(this.javaHome))
switch (this.sourceType) {
case CLASSFILES:
case JAR:
case APK:
this.javaHome = System.getenv("JAVA_HOME").replaceAll("//", "/");
break;
case JAVAFILES:
case DIR:
this.javaHome = System.getenv("JAVA7_HOME").replaceAll("//", "/");
break;
}
return this.javaHome;
}
/**
* addToDepth_Count.
*
* @param item a {@link java.lang.String} object.
*/
public void addToDepth_Count(String item) {
this.getHeuristics().addDepthCount(item);
//this.DEPTH_COUNT.add(item);
}
/** startAnalysis. */
public void startAnalysis() {
this.startAnalyisisTime = System.currentTimeMillis();
}
/** stopAnalysis. */
public void stopAnalysis() {
this.analysisMilliSeconds = System.currentTimeMillis() - this.startAnalyisisTime;
}
/**
* Getter for sootErrors
*
* <p>getSootErrors()
*
* @return a {@link java.lang.String} object.
*/
public String getSootErrors() {
return StringUtils.trimToEmpty(sootErrors.toString());
}
/**
* startScanning.
*
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void startScanning() throws ExceptionHandler {
this.getOutput().startAnalyzing();
this.startAnalysis();
}
/**
* stopScanning.
*
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void stopScanning() throws ExceptionHandler {
this.stopAnalysis();
this.setHuristicsInfo();
if (this.getHeuristicsHandler() != null)
log.info(this.getHeuristicsHandler().apply(this.getHeuristics()));
this.getOutput().stopAnalyzing();
}
/**
* Getter for the field <code>output</code>.
*
* @return a {@link frontEnd.MessagingSystem.routing.outputStructures.OutputStructure} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public OutputStructure getOutput() throws ExceptionHandler {
if (this.output == null)
this.output = this.messagingType.getTypeOfMessagingOutput(this.streaming, this);
return this.output;
}
/**
* getSLICE_AVERAGE_3SigFig.
*
* @return a double.
*/
public double getSLICE_AVERAGE_3SigFig() {
return this.getHeuristics().getSliceAverage();
}
/**
* getUUID.
*
* @return a {@link java.lang.String} object.
*/
public String getUUID() {
if (this.UUID == null) this.UUID = java.util.UUID.randomUUID().toString();
return this.UUID;
}
/**
* Getter for the field <code>buildId</code>.
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getBuildId() {
if (this.buildId == null) this.buildId = 0;
return buildId;
}
/**
* Getter for sourceDependencies
*
* <p>getDependencies()
*
* @return a String object.
*/
public List<String> getDependencies() {
if (dependencies == null) dependencies = new ArrayList<>();
return dependencies;
}
/**
* getMessagingOutput.
*
* @return a {@link frontEnd.MessagingSystem.routing.outputStructures.OutputStructure} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public OutputStructure getMessagingOutput() throws ExceptionHandler {
if (this.output == null)
this.output = messagingType.getTypeOfMessagingOutput(this.streaming, this);
return this.output;
}
/**
* Setter for packageRootDir
*
* <p>setPackageRootDir(java.lang.String packageRootDir)
*
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void setPackageRootDir() throws ExceptionHandler {
log.info("Building the Package Root Dir based on type");
switch (this.getSourceType()) {
/*case APK:
this.packageRootDir = Utils.getBasePackageNameFromApk(this.getSource().get(0));
this.packageRootDir = this.getSource().get(0);
break;
case DIR:
String[] splitPart = this.getSource().get(0).split(Utils.fileSep);
this.packageRootDir = splitPart[splitPart.length - 1].replaceAll(":dir",Utils.fileSep);
break;
case JAR:
File jar = new File(this.getSource().get(0));
this.packageRootDir = this.getSource().get(0); //Utils.getBasePackageNameFromJar(jar.getAbsolutePath(),true);*/
case JAR:
case DIR:
case APK:
String[] split = this.getSource().get(0).split(Utils.fileSep);
this.packageRootDir = split[split.length - 1] + Utils.fileSep;
break;
case JAVAFILES:
case CLASSFILES:
this.packageRootDir = Utils.getRelativeFilePath(packageRootDir);
break;
}
}
/**
* Setter for buildRootDir
*
* <p>setBuildRootDir(java.lang.String buildRootDir)
*
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void setBuildRootDir() throws ExceptionHandler {
log.info("Building the Root Directory");
try {
switch (this.getSourceType()) {
case APK:
case DIR:
case JAR:
this.buildRootDir = new File(sourcePaths.get(0)).getCanonicalPath();
break;
case JAVAFILES:
case CLASSFILES:
this.buildRootDir = Utils.retrievePackageFromJavaFiles(sourcePaths);
break;
}
} catch (IOException e) {
log.fatal("Error reading file: " + buildRootDir);
throw new ExceptionHandler("Error reading file: " + buildRootDir, ExceptionId.FILE_I);
}
}
/**
* getFileOutName.
*
* @return a {@link java.lang.String} object.
*/
public String getFileOutName() {
String[] split = this.fileOut.split(System.getProperty("file.separator"));
return split[split.length - 1];
}
public String getComputerOS() {
return Utils.getPlatform();
}
public String getJVM() {
return Utils.getJVMInfo();
}
//endregion
//region Helpful Methods
/** setHuristicsInfo. */
public void setHuristicsInfo() {
this.heuristics.setNumberOfOrthogonal(Utils.NUM_ORTHOGONAL);
this.heuristics.setNumberOfConstantsToCheck(Utils.NUM_CONSTS_TO_CHECK);
this.heuristics.setNumberOfSlices(Utils.NUM_SLICES);
this.heuristics.setNumberOfHeuristics(Utils.NUM_HEURISTIC);
this.heuristics.setSliceAverage(Utils.calculateAverage());
this.heuristics.setDepthCount(Utils.createDepthCountList());
}
/**
* getProperties.
*
* @return a {@link java.util.Properties} object.
*/
public Properties getProperties() {
return this.Properties;
}
/**
* getPropertiesFile.
*
* @return a {@link java.lang.String} object.
*/
public String getPropertiesFile() {
return this.PropertiesFile;
}
/**
* getToolFramework.
*
* @return a {@link java.lang.String} object.
*/
public String getToolFramework() {
return this.ToolFramework;
}
/**
* getToolFrameworkVersion.
*
* @return a {@link java.lang.String} object.
*/
public String getToolFrameworkVersion() {
return this.ToolFrameworkVersion;
}
/**
* Getter for the field <code>platformName</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getPlatformName() {
return this.platformName;
}
/**
* getSource.
*
* @return a {@link java.util.List} object.
*/
public List<String> getSource() {
return this.Source;
}
/**
* Getter for the field <code>sourcePaths</code>.
*
* @return a {@link java.util.List} object.
*/
public List<String> getSourcePaths() {
return this.sourcePaths;
}
/**
* getBuildFramework.
*
* @return a {@link java.lang.String} object.
*/
public String getBuildFramework() {
return this.BuildFramework;
}
/**
* getBuildFrameworkVersion.
*
* @return a {@link java.lang.String} object.
*/
public String getBuildFrameworkVersion() {
return this.BuildFrameworkVersion;
}
/**
* Getter for the field <code>packageName</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getPackageName() {
return this.packageName;
}
/**
* Getter for the field <code>packageVersion</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getPackageVersion() {
return this.packageVersion;
}
/**
* isShowTimes.
*
* @return a boolean.
*/
public boolean isShowTimes() {
return this.showTimes;
}
/**
* isAddExperimentalRules.
*
* @return a boolean.
*/
public boolean isAddExperimentalRules() {
return this.addExperimentalRules;
}
/**
* Getter for the field <code>rawCommand</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getRawCommand() {
return this.rawCommand;
}
/**
* Getter for the field <code>main</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getMain() {
return this.main;
}
/**
* isOverWriteOutput.
*
* @return a boolean.
*/
public boolean isOverWriteOutput() {
return this.overWriteOutput;
}
/**
* Getter for the field <code>targetProjectName</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getTargetProjectName() {
return this.targetProjectName;
}
/**
* Getter for the field <code>targetProjectVersion</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getTargetProjectVersion() {
return this.targetProjectVersion;
}
/**
* Getter for the field <code>isGradle</code>.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean getIsGradle() {
return this.isGradle;
}
/**
* Getter for the field <code>prettyPrint</code>.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean getPrettyPrint() {
return this.prettyPrint;
}
/**
* Getter for the field <code>killJVM</code>.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean getKillJVM() {
return this.killJVM;
}
/**
* Getter for the field <code>sourceType</code>.
*
* @return a {@link rule.engine.EngineType} object.
*/
public EngineType getSourceType() {
return this.sourceType;
}
/**
* Getter for the field <code>messagingType</code>.
*
* @return a {@link frontEnd.MessagingSystem.routing.Listing} object.
*/
public Listing getMessagingType() {
return this.messagingType;
}
/**
* Getter for the field <code>startAnalyisisTime</code>.
*
* @return a {@link java.lang.Long} object.
*/
public Long getStartAnalyisisTime() {
return this.startAnalyisisTime;
}
/**
* Getter for the field <code>analysisMilliSeconds</code>.
*
* @return a {@link java.lang.Long} object.
*/
public Long getAnalysisMilliSeconds() {
return this.analysisMilliSeconds;
}
/**
* Getter for the field <code>fileOut</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getFileOut() {
return this.fileOut;
}
/**
* Getter for the field <code>streaming</code>.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean getStreaming() {
return this.streaming;
}
/**
* getAssessmentFramework.
*
* @return a {@link java.lang.String} object.
*/
public String getAssessmentFramework() {
return this.AssessmentFramework;
}
/**
* getAssessmentFrameworkVersion.
*
* @return a {@link java.lang.String} object.
*/
public String getAssessmentFrameworkVersion() {
return this.AssessmentFrameworkVersion;
}
/**
* Getter for the field <code>formatter</code>.
*
* @return a {@link java.time.format.DateTimeFormatter} object.
*/
public DateTimeFormatter getFormatter() {
return this.formatter;
}
/**
* getAssessmentStartTime.
*
* @return a {@link java.lang.String} object.
*/
public String getAssessmentStartTime() {
return this.AssessmentStartTime;
}
/**
* getParserName.
*
* @return a {@link java.lang.String} object.
*/
public String getParserName() {
return this.ParserName;
}
/**
* getParserVersion.
*
* @return a {@link java.lang.String} object.
*/
public String getParserVersion() {
return this.ParserVersion;
}
/**
* Getter for the field <code>packageRootDir</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getPackageRootDir() {
return this.packageRootDir;
}
/**
* Getter for the field <code>buildRootDir</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getBuildRootDir() {
return this.buildRootDir;
}
/**
* Getter for the field <code>xPath</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getXPath() {
return this.xPath;
}
/**
* Getter for the field <code>printOut</code>.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean getPrintOut() {
return this.printOut;
}
/**
* Getter for the field <code>displayHeuristics</code>.
*
* @return a {@link java.lang.Boolean} object.
*/
public Boolean getDisplayHeuristics() {
return this.displayHeuristics;
}
/**
* Getter for the field <code>heuristics</code>.
*
* @return a {@link frontEnd.MessagingSystem.routing.outputStructures.common.Heuristics} object.
*/
public Heuristics getHeuristics() {
return this.heuristics;
}
/**
* Getter for the field <code>errorAddition</code>.
*
* @return a {@link java.util.function.Function} object.
*/
public Function<AnalysisIssue, String> getErrorAddition() {
return this.errorAddition;
}
/**
* Getter for the field <code>bugSummaryHandler</code>.
*
* @return a {@link java.util.function.Function} object.
*/
public Function<HashMap<Integer, Integer>, String> getBugSummaryHandler() {
return this.bugSummaryHandler;
}
/**
* Getter for the field <code>heuristicsHandler</code>.
*
* @return a {@link java.util.function.Function} object.
*/
public Function<Heuristics, String> getHeuristicsHandler() {
return this.heuristicsHandler;
}
/**
* setToolFramework.
*
* @param ToolFramework a {@link java.lang.String} object.
*/
public void setToolFramework(String ToolFramework) {
this.ToolFramework = ToolFramework;
}
/**
* setToolFrameworkVersion.
*
* @param ToolFrameworkVersion a {@link java.lang.String} object.
*/
public void setToolFrameworkVersion(String ToolFrameworkVersion) {
this.ToolFrameworkVersion = ToolFrameworkVersion;
}
/**
* Setter for the field <code>platformName</code>.
*
* @param platformName a {@link java.lang.String} object.
*/
public void setPlatformName(String platformName) {
this.platformName = platformName;
}
/**
* setBuildFramework.
*
* @param BuildFramework a {@link java.lang.String} object.
*/
public void setBuildFramework(String BuildFramework) {
this.BuildFramework = BuildFramework;
}
/**
* setBuildFrameworkVersion.
*
* @param BuildFrameworkVersion a {@link java.lang.String} object.
*/
public void setBuildFrameworkVersion(String BuildFrameworkVersion) {
this.BuildFrameworkVersion = BuildFrameworkVersion;
}
/**
* Setter for the field <code>packageName</code>.
*
* @param packageName a {@link java.lang.String} object.
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
/**
* Setter for the field <code>packageVersion</code>.
*
* @param packageVersion a {@link java.lang.String} object.
*/
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
/**
* Setter for the field <code>showTimes</code>.
*
* @param showTimes a boolean.
*/
public void setShowTimes(boolean showTimes) {
this.showTimes = showTimes;
}
/**
* Setter for the field <code>addExperimentalRules</code>.
*
* @param addExperimentalRules a boolean.
*/
public void setAddExperimentalRules(boolean addExperimentalRules) {
this.addExperimentalRules = addExperimentalRules;
}
/**
* Setter for the field <code>rawCommand</code>.
*
* @param rawCommand a {@link java.lang.String} object.
*/
public void setRawCommand(String rawCommand) {
this.rawCommand = rawCommand;
}
/**
* Setter for the field <code>main</code>.
*
* @param main a {@link java.lang.String} object.
*/
public void setMain(String main) {
this.main = main;
}
/**
* Setter for the field <code>overWriteOutput</code>.
*
* @param overWriteOutput a boolean.
*/
public void setOverWriteOutput(boolean overWriteOutput) {
this.overWriteOutput = overWriteOutput;
}
/**
* Setter for the field <code>targetProjectName</code>.
*
* @param targetProjectName a {@link java.lang.String} object.
*/
public void setTargetProjectName(String targetProjectName) {
this.targetProjectName = targetProjectName;
}
/**
* Setter for the field <code>targetProjectVersion</code>.
*
* @param targetProjectVersion a {@link java.lang.String} object.
*/
public void setTargetProjectVersion(String targetProjectVersion) {
this.targetProjectVersion = targetProjectVersion;
}
/**
* Setter for the field <code>isGradle</code>.
*
* @param isGradle a {@link java.lang.Boolean} object.
*/
public void setIsGradle(Boolean isGradle) {
this.isGradle = isGradle;
}
/**
* Setter for the field <code>prettyPrint</code>.
*
* @param prettyPrint a {@link java.lang.Boolean} object.
*/
public void setPrettyPrint(Boolean prettyPrint) {
this.prettyPrint = prettyPrint;
}
/**
* Setter for the field <code>killJVM</code>.
*
* @param killJVM a {@link java.lang.Boolean} object.
*/
public void setKillJVM(Boolean killJVM) {
this.killJVM = killJVM;
}
/**
* Setter for the field <code>dependencies</code>.
*
* @param dependencies a {@link java.util.List} object.
*/
public void setDependencies(List<String> dependencies) {
this.dependencies = dependencies;
}
/**
* Setter for the field <code>sourceType</code>.
*
* @param sourceType a {@link rule.engine.EngineType} object.
*/
public void setSourceType(EngineType sourceType) {
this.sourceType = sourceType;
}
/**
* Setter for the field <code>messagingType</code>.
*
* @param messagingType a {@link frontEnd.MessagingSystem.routing.Listing} object.
*/
public void setMessagingType(Listing messagingType) {
this.messagingType = messagingType;
}
/**
* setUUID.
*
* @param UUID a {@link java.lang.String} object.
*/
public void setUUID(String UUID) {
this.UUID = UUID;
}
/**
* Setter for the field <code>startAnalyisisTime</code>.
*
* @param startAnalyisisTime a {@link java.lang.Long} object.
*/
public void setStartAnalyisisTime(Long startAnalyisisTime) {
this.startAnalyisisTime = startAnalyisisTime;
}
/**
* Setter for the field <code>analysisMilliSeconds</code>.
*
* @param analysisMilliSeconds a {@link java.lang.Long} object.
*/
public void setAnalysisMilliSeconds(Long analysisMilliSeconds) {
this.analysisMilliSeconds = analysisMilliSeconds;
}
/**
* Setter for the field <code>fileOut</code>.
*
* @param fileOut a {@link java.lang.String} object.
*/
public void setFileOut(String fileOut) {
this.fileOut = fileOut;
}
/**
* Setter for the field <code>streaming</code>.
*
* @param streaming a {@link java.lang.Boolean} object.
*/
public void setStreaming(Boolean streaming) {
this.streaming = streaming;
}
/**
* Setter for the field <code>javaHome</code>.
*
* @param javaHome a {@link java.lang.String} object.
*/
public void setJavaHome(String javaHome) {
this.javaHome = javaHome;
}
/**
* Setter for the field <code>androidHome</code>.
*
* @param androidHome a {@link java.lang.String} object.
*/
public void setAndroidHome(String androidHome) {
this.androidHome = androidHome;
}
/**
* setAssessmentFramework.
*
* @param AssessmentFramework a {@link java.lang.String} object.
*/
public void setAssessmentFramework(String AssessmentFramework) {
this.AssessmentFramework = AssessmentFramework;
}
/**
* setAssessmentFrameworkVersion.
*
* @param AssessmentFrameworkVersion a {@link java.lang.String} object.
*/
public void setAssessmentFrameworkVersion(String AssessmentFrameworkVersion) {
this.AssessmentFrameworkVersion = AssessmentFrameworkVersion;
}
/**
* Setter for the field <code>formatter</code>.
*
* @param formatter a {@link java.time.format.DateTimeFormatter} object.
*/
public void setFormatter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
/**
* setAssessmentStartTime.
*
* @param AssessmentStartTime a {@link java.lang.String} object.
*/
public void setAssessmentStartTime(String AssessmentStartTime) {
this.AssessmentStartTime = AssessmentStartTime;
}
/**
* setParserName.
*
* @param ParserName a {@link java.lang.String} object.
*/
public void setParserName(String ParserName) {
this.ParserName = ParserName;
}
/**
* setParserVersion.
*
* @param ParserVersion a {@link java.lang.String} object.
*/
public void setParserVersion(String ParserVersion) {
this.ParserVersion = ParserVersion;
}
/**
* Setter for the field <code>packageRootDir</code>.
*
* @param packageRootDir a {@link java.lang.String} object.
*/
public void setPackageRootDir(String packageRootDir) {
this.packageRootDir = packageRootDir;
}
/**
* Setter for the field <code>buildRootDir</code>.
*
* @param buildRootDir a {@link java.lang.String} object.
*/
public void setBuildRootDir(String buildRootDir) {
this.buildRootDir = buildRootDir;
}
/**
* Setter for the field <code>buildId</code>.
*
* @param buildId a {@link java.lang.Integer} object.
*/
public void setBuildId(Integer buildId) {
this.buildId = buildId;
}
/**
* Setter for the field <code>xPath</code>.
*
* @param xPath a {@link java.lang.String} object.
*/
public void setXPath(String xPath) {
this.xPath = xPath;
}
/**
* Setter for the field <code>printOut</code>.
*
* @param printOut a {@link java.lang.Boolean} object.
*/
public void setPrintOut(Boolean printOut) {
this.printOut = printOut;
}
/**
* Setter for the field <code>output</code>.
*
* @param output a {@link frontEnd.MessagingSystem.routing.outputStructures.OutputStructure}
* object.
*/
public void setOutput(OutputStructure output) {
this.output = output;
}
/**
* Setter for the field <code>sootErrors</code>.
*
* @param sootErrors a {@link java.io.ByteArrayOutputStream} object.
*/
public void setSootErrors(ByteArrayOutputStream sootErrors) {
this.sootErrors = sootErrors;
}
/**
* Setter for the field <code>displayHeuristics</code>.
*
* @param displayHeuristics a {@link java.lang.Boolean} object.
*/
public void setDisplayHeuristics(Boolean displayHeuristics) {
this.displayHeuristics = displayHeuristics;
}
/**
* Setter for the field <code>heuristics</code>.
*
* @param heuristics a {@link frontEnd.MessagingSystem.routing.outputStructures.common.Heuristics}
* object.
*/
public void setHeuristics(Heuristics heuristics) {
this.heuristics = heuristics;
}
/**
* Setter for the field <code>errorAddition</code>.
*
* @param errorAddition a {@link java.util.function.Function} object.
*/
public void setErrorAddition(Function<AnalysisIssue, String> errorAddition) {
this.errorAddition = errorAddition;
}
/**
* Setter for the field <code>bugSummaryHandler</code>.
*
* @param bugSummaryHandler a {@link java.util.function.Function} object.
*/
public void setBugSummaryHandler(Function<HashMap<Integer, Integer>, String> bugSummaryHandler) {
this.bugSummaryHandler = bugSummaryHandler;
}
/**
* Setter for the field <code>heuristicsHandler</code>.
*
* @param heuristicsHandler a {@link java.util.function.Function} object.
*/
public void setHeuristicsHandler(Function<Heuristics, String> heuristicsHandler) {
this.heuristicsHandler = heuristicsHandler;
}
//endregion
}
| 32,225 | 24.863563 | 123 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/Listing.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing;
import frontEnd.Interface.formatArgument.TypeSpecificArg;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import frontEnd.MessagingSystem.routing.outputStructures.OutputStructure;
import frontEnd.MessagingSystem.routing.outputStructures.block.Structure;
import frontEnd.MessagingSystem.routing.outputStructures.common.JacksonSerializer;
import frontEnd.MessagingSystem.routing.outputStructures.stream.Legacy;
import frontEnd.argsIdentifier;
import java.util.List;
import org.apache.logging.log4j.Logger;
/**
* The enum containing all of the different messaging types available for the user.
*
* @author franceme
* @version 03.07.01
* @since V01.00.00
*/
public enum Listing {
//region Values
Legacy("Legacy", "L", ".txt", true, null),
ScarfXML("ScarfXML", "SX", null, true, JacksonSerializer.JacksonType.XML),
Default("Default", "D", null, true, JacksonSerializer.JacksonType.JSON),
YAMLGeneric("Default", "Y", null, true, JacksonSerializer.JacksonType.YAML),
XMLGeneric("Default", "X", null, true, JacksonSerializer.JacksonType.XML),
CSVDefault("CSVDefault", "CSV", ".csv", true, null);
//endregion
//region Attributes
private final String blockPath = "frontEnd.MessagingSystem.routing.outputStructures.block.";
private final String inputPath = "frontEnd.MessagingSystem.routing.inputStructures";
private final String streamPath = "frontEnd.MessagingSystem.routing.outputStructures.stream.";
private final String typeSpecificArgPath = "frontEnd.Interface.formatArgument.";
private String type;
private String flag;
private String outputFileExt;
private Boolean streamEnabled;
private JacksonSerializer.JacksonType jacksonType;
private Logger log;
//endregion
//region Constructor
/**
* The inherint constructor of all the enum value types listed here
*
* @param Type - the string value of the type of
* @param Flag - the flag used to identify the specific messaging type
*/
Listing(
String Type,
String Flag,
String outputFileExt,
Boolean streamed,
JacksonSerializer.JacksonType jacksonType) {
this.type = Type;
this.flag = Flag;
this.outputFileExt = outputFileExt;
this.streamEnabled = streamed;
this.jacksonType = jacksonType;
this.log = org.apache.logging.log4j.LogManager.getLogger(EnvironmentInformation.class);
}
//endregion
//region Overridden Methods
/**
* getInputFullHelp.
*
* @return a {@link java.lang.String} object.
*/
public static String getInputFullHelp() {
StringBuilder out = new StringBuilder();
for (Listing listingType : Listing.values()) {
/*
try {
out.append(listingType.retrieveSpecificArgHandler().helpInfo()).append("\n");
} catch (ExceptionHandler e) {}
*/
}
return out.toString();
}
//endregion
//region Getter
/**
* The dynamic loader for the Listing Type based on the flag
*
* @param flag {@link java.lang.String} - The input type looking for the flag type
* @return {@link frontEnd.MessagingSystem.routing.Listing} - The messaging Type retrieved by
* flag, if not found the default will be used
*/
public static Listing retrieveListingType(String flag) {
if (flag != null) for (Listing type : Listing.values()) if (type.flag.equals(flag)) return type;
return Listing.Default;
}
/**
* getShortHelp.
*
* @return a {@link java.lang.String} object.
*/
public static String getShortHelp() {
StringBuilder helpString = new StringBuilder("{");
for (Listing in : Listing.values())
helpString.append(in.getType()).append(": ").append(in.getFlag()).append(", ");
helpString.append("}");
return helpString.toString();
}
/**
* Getter for flag
*
* <p>getFlag()
*
* @return a {@link java.lang.String} object.
*/
public String getFlag() {
return flag;
}
/**
* retrieveArgs.
*
* @return a {@link java.util.List} object.
*/
public List<argsIdentifier> retrieveArgs() {
return argsIdentifier.lookup(this);
}
//endregion
//region Helpers Based on the enum type
//region Output Helpers
/**
* Getter for type
*
* <p>getType()
*
* @return {@link java.lang.String} - The type.
*/
public String getType() {
return type;
}
/** {@inheritDoc} */
@Override
public String toString() {
return "{ \"type\": \"" + this.type + "\", \"flag\": \"" + this.flag + "\"}";
}
//endregion
//region InputHelpers
/**
* getTypeOfMessagingOutput.
*
* @param stream a boolean.
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
* @return a {@link frontEnd.MessagingSystem.routing.outputStructures.OutputStructure} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public OutputStructure getTypeOfMessagingOutput(boolean stream, EnvironmentInformation info)
throws ExceptionHandler {
if (stream) {
if (!this.streamEnabled) {
log.info("Streaming is not supported for the format: " + this.getType());
log.info("Defaulting back to block based output.");
return getTypeOfMessagingOutput(false, info);
} else {
try {
return (frontEnd.MessagingSystem.routing.outputStructures.stream.Structure)
Class.forName(this.streamPath + this.type)
.getConstructor(EnvironmentInformation.class)
.newInstance(info);
} catch (Exception e) {
return new Legacy(info);
}
}
} else //non-streamed
{
try {
return (Structure)
Class.forName(this.blockPath + this.type)
.getConstructor(EnvironmentInformation.class)
.newInstance(info);
} catch (Exception e) {
return new frontEnd.MessagingSystem.routing.outputStructures.block.Legacy(info);
}
}
}
/**
* unmarshall.
*
* @param stream a boolean.
* @param filePath a {@link java.lang.String} object.
* @return a {@link frontEnd.MessagingSystem.routing.outputStructures.OutputStructure} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public OutputStructure unmarshall(boolean stream, String filePath) throws ExceptionHandler {
if (stream) {
if (!this.streamEnabled) {
log.info("Streaming is not supported for the format: " + this.getType());
log.info("Defaulting to block based output.");
return unmarshall(false, filePath);
} else {
try {
return (frontEnd.MessagingSystem.routing.outputStructures.stream.Structure)
Class.forName(this.streamPath + this.type)
.getConstructor(String.class)
.newInstance(filePath);
} catch (Exception e) {
log.fatal(
"Issue dynamically calling the stream TypeSpecificArg with the filepath: "
+ filePath);
throw new ExceptionHandler(
ExceptionId.ARG_VALID,
"Issue dynamically calling the TypeSpecificArg with the filepath: " + filePath);
}
}
} else //non-streamed
{
try {
return (Structure)
Class.forName(this.blockPath + this.type)
.getConstructor(String.class)
.newInstance(filePath);
} catch (Exception e) {
log.fatal(
"Issue dynamically calling the blocked TypeSpecificArg with the filepath: " + filePath);
throw new ExceptionHandler(
ExceptionId.ARG_VALID,
"Issue dynamically calling the TypeSpecificArg with the filepath: " + filePath);
}
}
}
/**
* retrieveSpecificArgHandler.
*
* @return a {@link frontEnd.Interface.formatArgument.TypeSpecificArg} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public TypeSpecificArg retrieveSpecificArgHandler() throws ExceptionHandler {
try {
return (TypeSpecificArg)
Class.forName(this.typeSpecificArgPath + this.type).getConstructor().newInstance();
} catch (Exception e) {
log.warn(
"Issue dynamically calling the specific argument validator: "
+ this.typeSpecificArgPath
+ this.type);
throw new ExceptionHandler(
ExceptionId.ENV_VAR,
"Issue dynamically calling the specific argument validator: "
+ this.typeSpecificArgPath
+ this.type);
}
}
/**
* Getter for the field <code>outputFileExt</code>.
*
* @return a {@link java.lang.String} object.
*/
public String getOutputFileExt() {
if (outputFileExt == null) return this.jacksonType.getExtension();
else return outputFileExt;
}
/**
* Getter for the field <code>jacksonType</code>.
*
* @return a {@link
* frontEnd.MessagingSystem.routing.outputStructures.common.JacksonSerializer.JacksonType}
* object.
*/
public JacksonSerializer.JacksonType getJacksonType() {
return jacksonType;
}
//endregion
//endregion
}
| 9,255 | 29.956522 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/OutputStructure.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures;
import CWE_Reader.CWEList;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.structure.Scarf.BugCategory;
import frontEnd.MessagingSystem.routing.structure.Scarf.BugSummary;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.function.Function;
import org.apache.logging.log4j.Logger;
import rule.engine.EngineType;
import rule.engine.RuleList;
/**
* Abstract OutputStructure class.
*
* @author CryptoguardTeam Created on 3/1/19.
* @version 03.07.01
* @since 03.03.00
* <p>The general class encompassing the output structure (stream and blocked).
*/
public abstract class OutputStructure {
private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(OutputStructure.class);
//region Attributes
private EnvironmentInformation source;
private final ArrayList<AnalysisIssue> collection;
private File outfile;
private EngineType type;
private final CWEList cwes = new CWEList();
private final Charset chars = StandardCharsets.UTF_8;
private final HashMap<Integer, Integer> countOfBugs = new HashMap<>();
private final Function<AnalysisIssue, String> errorAddition;
private final Function<HashMap<Integer, Integer>, String> bugSummaryHandler;
//endregion
//region Constructors
/**
* Constructor for OutputStructure.
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public OutputStructure(EnvironmentInformation info) {
this.source = info;
this.outfile = new File(info.getFileOut());
this.type = info.getSourceType();
this.collection = new ArrayList<>();
this.errorAddition = info.getErrorAddition();
this.bugSummaryHandler = info.getBugSummaryHandler();
}
/** Constructor for OutputStructure. */
public OutputStructure() {
this.collection = new ArrayList<>();
this.errorAddition = null;
this.bugSummaryHandler = null;
}
//endregion
//region Methods to be overridden
/**
* startAnalyzing.
*
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public abstract void startAnalyzing() throws ExceptionHandler;
private void addIssueCore(AnalysisIssue issue) throws ExceptionHandler {
if (this.errorAddition != null) log.info(this.errorAddition.apply(issue));
log.debug("Adding Issue: " + issue.getInfo());
//Keeping a rolling count of the different kinds of bugs occuring
if (!countOfBugs.containsKey(issue.getRuleId())) {
countOfBugs.put(issue.getRuleId(), 1);
} else {
countOfBugs.put(issue.getRuleId(), countOfBugs.get(issue.getRuleId()) + 1);
}
}
/**
* addIssue.
*
* @param issue a {@link frontEnd.MessagingSystem.AnalysisIssue} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void addIssue(AnalysisIssue issue) throws ExceptionHandler {
this.addIssueCore(issue);
}
/**
* addIssueToCollection.
*
* @param issue a {@link frontEnd.MessagingSystem.AnalysisIssue} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void addIssueToCollection(AnalysisIssue issue) throws ExceptionHandler {
this.addIssueCore(issue);
this.collection.add(issue);
}
/**
* stopAnalyzing.
*
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public abstract void stopAnalyzing() throws ExceptionHandler;
//endregion
//region Public helper methods
/**
* createBugCategoryList.
*
* @return a {@link frontEnd.MessagingSystem.routing.structure.Scarf.BugSummary} object.
*/
public BugSummary createBugCategoryList() {
log.debug("Creating the Bug Summary");
BugSummary bugDict = new BugSummary();
//region Creating A Bug Category with counts per the Broken Rules
for (int ruleNumber : countOfBugs.keySet()) {
BugCategory ruleType = new BugCategory();
ruleType.setGroup(RuleList.getRuleByRuleNumber(ruleNumber).getDesc());
ruleType.setCode(String.valueOf(ruleNumber));
ruleType.setCount(countOfBugs.get(ruleNumber));
if (countOfBugs.get(ruleNumber) > 0) bugDict.addBugSummary(ruleType);
log.debug("Added ruleType: " + ruleType.toString());
}
//endregion
if (this.bugSummaryHandler != null) log.info(this.bugSummaryHandler.apply(countOfBugs));
return bugDict;
}
/**
* Getter for the field <code>source</code>.
*
* @return a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public EnvironmentInformation getSource() {
return source;
}
/**
* Getter for the field <code>collection</code>.
*
* @return a {@link java.util.ArrayList} object.
*/
public ArrayList<AnalysisIssue> getCollection() {
return collection;
}
/**
* Getter for the field <code>outfile</code>.
*
* @return a {@link java.io.File} object.
*/
public File getOutfile() {
return outfile;
}
/**
* Getter for the field <code>type</code>.
*
* @return a {@link rule.engine.EngineType} object.
*/
public EngineType getType() {
return type;
}
/**
* Getter for the field <code>chars</code>.
*
* @return a {@link java.nio.charset.Charset} object.
*/
public Charset getChars() {
return chars;
}
/**
* Getter for the field <code>countOfBugs</code>.
*
* @return a {@link java.util.HashMap} object.
*/
public HashMap<Integer, Integer> getCountOfBugs() {
return countOfBugs;
}
/**
* Getter for the field <code>cwes</code>.
*
* @return a {@link CWE_Reader.CWEList} object.
*/
public CWEList getCwes() {
return cwes;
}
/**
* Setter for the field <code>source</code>.
*
* @param source a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public void setSource(EnvironmentInformation source) {
this.source = source;
}
/**
* Setter for the field <code>outfile</code>.
*
* @param outfile a {@link java.io.File} object.
*/
public void setOutfile(File outfile) {
this.outfile = outfile;
}
/**
* Setter for the field <code>type</code>.
*
* @param type a {@link rule.engine.EngineType} object.
*/
public void setType(EngineType type) {
this.type = type;
}
//endregion
}
| 6,629 | 26.740586 | 92 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/block/CSVDefault.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures.block;
import static frontEnd.MessagingSystem.routing.outputStructures.common.Default.mapper;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.outputStructures.common.CSVMapper;
import frontEnd.MessagingSystem.routing.structure.Default.Report;
import java.io.File;
import org.apache.logging.log4j.Logger;
/**
* Default class.
*
* @author franceme Created on 04/30/2019.
* @version 03.07.01
* @since 03.05.01
* <p>{Description Here}
*/
public class CSVDefault extends Structure {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(CSVDefault.class);
//region Attributes
public final CSVMapper mapper;
/**
* {@inheritDoc}
*
* @param info a {@link EnvironmentInformation} object.
*/
public CSVDefault(EnvironmentInformation info) {
super(info);
mapper = new CSVMapper(info);
}
/**
* Constructor for Default.
*
* @param filePath a {@link String} object.
* @throws ExceptionHandler if any.
*/
public CSVDefault(String filePath) throws ExceptionHandler {
Report struct = Report.deserialize(new File(filePath));
EnvironmentInformation info = mapper(struct);
mapper = new CSVMapper(info);
super.setSource(info);
super.setOutfile(new File(info.getFileOut()));
super.setType(mapper(struct.getTarget().getType()));
for (frontEnd.MessagingSystem.routing.structure.Default.Issue issue : struct.getIssues())
super.addIssueToCollection(mapper(issue));
}
//endregion
//region Constructor
//endregion
//region Overridden Methods
/** {@inheritDoc} */
@Override
public String handleOutput() throws ExceptionHandler {
StringBuilder contents = new StringBuilder();
//region Setting the report for marshalling
log.info("Marshalling the Report from the Env. Info.");
contents.append(mapper.writeHeader()).append("\n");
//region Creating Bug Instances
log.debug("Adding all of the collected issues");
for (AnalysisIssue in : super.getCollection()) {
log.debug("Marshalling and adding the issue: " + in.getInfo());
contents.append(mapper.writeIssue(in)).append("\n");
}
//endregion
return contents.toString();
}
//endregion
}
| 2,463 | 27 | 100 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/block/Default.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures.block;
import static frontEnd.MessagingSystem.routing.outputStructures.common.Default.mapper;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.outputStructures.common.JacksonSerializer;
import frontEnd.MessagingSystem.routing.structure.Default.Report;
import java.io.File;
import org.apache.logging.log4j.Logger;
import util.Utils;
/**
* Default class.
*
* @author franceme Created on 04/30/2019.
* @version 03.07.01
* @since 03.05.01
* <p>{Description Here}
*/
public class Default extends Structure {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(Default.class);
//region Attributes
/**
* {@inheritDoc}
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public Default(EnvironmentInformation info) {
super(info);
}
/**
* Constructor for Default.
*
* @param filePath a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public Default(String filePath) throws ExceptionHandler {
Report struct = Report.deserialize(new File(filePath));
EnvironmentInformation info = mapper(struct);
super.setSource(info);
super.setOutfile(new File(info.getFileOut()));
super.setType(mapper(struct.getTarget().getType()));
for (frontEnd.MessagingSystem.routing.structure.Default.Issue issue : struct.getIssues())
super.addIssueToCollection(mapper(issue));
}
//endregion
//region Constructor
//endregion
//region Overridden Methods
/** {@inheritDoc} */
@Override
public String handleOutput() throws ExceptionHandler {
//reopening the console stream
//region Setting the report for marshalling
log.info("Marshalling the Report from the Env. Info.");
Report report = mapper(super.getSource());
log.debug("Marshalling the Target Info from the Env. Info.");
report.setTarget(mapper(super.getSource(), Utils.getPlatform(), Utils.getJVMInfo()));
//region Creating Bug Instances
Integer bugCounter = 0;
log.debug("Adding all of the collected issues");
for (AnalysisIssue in : super.getCollection()) {
log.debug("Marshalling and adding the issue: " + in.getInfo());
report.getIssues().add(mapper(in, bugCounter));
bugCounter++;
}
//endregion
//region Heuristics
if (super.getSource().getDisplayHeuristics()) {
log.debug("Writing the heuristics");
report.setHeuristics(super.getSource().getHeuristics().getDefaultHeuristics());
}
//endregion
//endregion
//region Marshalling
log.debug("Creating the marshaller");
return JacksonSerializer.serialize(
report,
super.getSource().getPrettyPrint(),
super.getSource().getMessagingType().getJacksonType());
//endregion
}
//endregion
}
| 3,087 | 28.692308 | 97 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/block/Legacy.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures.block;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.outputStructures.OutputStructure;
import java.util.*;
import org.apache.logging.log4j.Logger;
import rule.engine.RuleList;
/**
* The class containing the implementation of the legacy output.
*
* <p>STATUS: IC
*
* @author franceme
* @version 03.07.01
* @since V01.00.01
*/
public class Legacy extends Structure {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(Legacy.class);
//region Attributes
/**
* {@inheritDoc}
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public Legacy(EnvironmentInformation info) {
super(info);
}
//endregion
//region Constructor
//endregion
//region Overridden Methods
/**
* deserialize.
*
* @param filePath a {@link java.lang.String} object.
* @return a {@link frontEnd.MessagingSystem.routing.outputStructures.OutputStructure} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public OutputStructure deserialize(String filePath) throws ExceptionHandler {
return null;
}
/** {@inheritDoc} */
@Override
public String handleOutput() throws ExceptionHandler {
StringBuilder output = new StringBuilder();
//reopening the console stream
log.debug("Writing the Header");
output.append(
frontEnd.MessagingSystem.routing.outputStructures.common.Legacy.marshallingHeader(
super.getType(), super.getSource().getSource()));
//Only printing console output if it is set and there is output captured
log.debug("Writing the Soot Errors");
output.append(
frontEnd.MessagingSystem.routing.outputStructures.common.Legacy.marshallingSootErrors(
super.getSource().getSootErrors()));
Map<Integer, List<AnalysisIssue>> groupedRules = new HashMap<>();
log.debug("Grouping all of the rules according by number.");
if (super.getCollection() != null)
for (AnalysisIssue issue : super.getCollection()) {
List<AnalysisIssue> tempList;
if (groupedRules.containsKey(issue.getRuleId())) {
tempList = new ArrayList<>(groupedRules.get(issue.getRuleId()));
tempList.add(issue);
} else {
tempList = Collections.singletonList(issue);
}
groupedRules.put(issue.getRuleId(), tempList);
}
//region Changing the order of the rules
Set<Integer> ruleOrdering = new HashSet<>();
log.debug("Ordering all of the rules based on the legacy output.");
if (true) {
Integer[] paperBasedOrdering = new Integer[] {3, 14, 6, 4, 12, 7, 11, 13, 9, 1, 10, 8, 5, 2};
for (Integer rule : paperBasedOrdering)
if (groupedRules.containsKey(rule)) ruleOrdering.add(rule);
} else ruleOrdering = groupedRules.keySet();
//endregion
//region Broken Rule Cycle
for (Integer ruleNumber : ruleOrdering) {
log.debug("Working through the rule group " + ruleNumber);
output.append("=======================================\n");
output
.append("***Violated Rule ")
.append(RuleList.getRuleByRuleNumber(ruleNumber).getRuleId())
.append(": ")
.append(RuleList.getRuleByRuleNumber(ruleNumber).getDesc())
.append("\n");
for (AnalysisIssue issue : groupedRules.get(ruleNumber)) {
log.debug("Working through the broken rule " + issue.getInfo());
output.append(
frontEnd.MessagingSystem.routing.outputStructures.common.Legacy.marshalling(
issue, super.getType()));
}
output.append("=======================================\n");
}
//endregion
//region Heuristics
if (super.getSource().getDisplayHeuristics()) {
log.debug("Writing the heuristics");
output.append(
frontEnd.MessagingSystem.routing.outputStructures.common.Legacy.marshalling(
super.getSource()));
}
//endregion
//region Timing Section
if (super.getSource().isShowTimes()) {
log.debug("Writing the time measurements.");
output.append(
frontEnd.MessagingSystem.routing.outputStructures.common.Legacy.marshalling(
super.getSource().getAnalysisMilliSeconds()));
}
//endregion
return output.toString();
}
//endregion
}
| 4,590 | 32.268116 | 99 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/block/ScarfXML.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures.block;
import static frontEnd.MessagingSystem.routing.outputStructures.common.ScarfXML.marshalling;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.Listing;
import frontEnd.MessagingSystem.routing.outputStructures.common.JacksonSerializer;
import frontEnd.MessagingSystem.routing.structure.Scarf.AnalyzerReport;
import frontEnd.MessagingSystem.routing.structure.Scarf.BugInstance;
import java.io.File;
import org.apache.logging.log4j.Logger;
/**
* The class containing the implementation of the Scarf XML output.
*
* <p>STATUS: IC
*
* @author franceme
* @version 03.07.01
* @since V01.00.03
*/
public class ScarfXML extends Structure {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ScarfXML.class);
//region Attributes
/**
* {@inheritDoc}
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public ScarfXML(EnvironmentInformation info) {
super(info);
}
/**
* Constructor for ScarfXML.
*
* @param filePath a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public ScarfXML(String filePath) throws ExceptionHandler {
AnalyzerReport report = AnalyzerReport.deserialize(new File(filePath));
EnvironmentInformation info = marshalling(report);
super.setSource(info);
super.setOutfile(new File(info.getFileOut()));
for (BugInstance instance : report.getBugInstance())
super.addIssueToCollection(marshalling(instance));
}
//endregion
//region Constructor
//endregion
//region Overridden Methods
/** {@inheritDoc} */
@Override
public String handleOutput() throws ExceptionHandler {
//reopening the console stream
//region Setting the report for marshalling
log.info("Marshalling the AnalyzerReport from the Env. Info.");
AnalyzerReport report = marshalling(super.getSource());
//region Creating Bug Instances
Integer numOfBugs = 0;
log.debug("Adding all of the collected issues");
for (AnalysisIssue in : super.getCollection()) {
log.debug("Marshalling and adding the issue: " + in.getInfo());
BugInstance marshalled =
marshalling(
in,
super.getCwes(),
super.getSource().getFileOutName(),
numOfBugs++,
super.getSource().getBuildId(),
super.getSource().getXPath());
report.getBugInstance().add(marshalled);
}
//endregion
log.info("Marshalling the bug category summary.");
report.setBugCategory(super.createBugCategoryList().getSummaryContainer());
//region Heuristics
if (super.getSource().getDisplayHeuristics()) {
log.debug("Writing the heuristics");
report.setHeuristics(super.getSource().getHeuristics().getScarfXMLHeuristics());
}
//endregion
//endregion
//region Marshalling
log.debug("Creating the marshaller");
String xmlStream =
JacksonSerializer.serialize(
report, super.getSource().getPrettyPrint(), Listing.ScarfXML.getJacksonType());
//endregion
String footer =
frontEnd.MessagingSystem.routing.outputStructures.common.ScarfXML.writeFooter(
super.getSource());
return xmlStream + footer;
}
//endregion
}
| 3,562 | 29.194915 | 98 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/block/Structure.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures.block;
import frontEnd.Interface.outputRouting.ExceptionHandler;
import frontEnd.Interface.outputRouting.ExceptionId;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.outputStructures.OutputStructure;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
/**
* Abstract TypeSpecificArg class.
*
* @author CryptoguardTeam Created on 3/2/19.
* @version 03.07.01
* @since 03.03.00
* <p>The overarching structure encompassing the block marshalling, extending from the output
* structure.
*/
public abstract class Structure extends OutputStructure {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(Structure.class);
//region Attributes
//endregion
//region Constructor
/**
* Constructor for TypeSpecificArg.
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public Structure(EnvironmentInformation info) {
super(info);
}
/** Constructor for TypeSpecificArg. */
public Structure() {}
//endregion
//region Overridden Methods
/** {@inheritDoc} */
@Override
public void startAnalyzing() {}
/** {@inheritDoc} */
@Override
public void addIssue(AnalysisIssue issue) throws ExceptionHandler {
super.addIssueToCollection(issue);
}
/** {@inheritDoc} */
@Override
public void stopAnalyzing() throws ExceptionHandler {
WriteIntoFile(StringUtils.stripToNull(this.handleOutput()));
}
//endregion
//region Self OverriddenMethods
/**
* handleOutput.
*
* @return a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public abstract String handleOutput() throws ExceptionHandler;
//endregion
//region Helper Methods
/**
* WriteIntoFile.
*
* @param in a {@link java.lang.String} object.
* @throws frontEnd.Interface.outputRouting.ExceptionHandler if any.
*/
public void WriteIntoFile(String in) throws ExceptionHandler {
try {
Files.write(this.getOutfile().toPath(), in.getBytes(super.getChars()));
} catch (IOException e) {
log.fatal("Error: " + e.getMessage());
throw new ExceptionHandler(
"Error writing to file: " + this.getSource().getFileOutName(), ExceptionId.FILE_O);
}
}
//endregion
}
| 2,564 | 26 | 99 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/common/CSVMapper.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures.common;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import org.apache.commons.lang3.StringEscapeUtils;
/**
* Default class.
*
* @author franceme Created on 4/23/19.
* @version 03.07.01
* @since 03.04.08
* <p>{Description Here}
*/
public class CSVMapper {
//region Constructor
public CSVMapper(EnvironmentInformation info) {
this.setProjectName(info.getTargetProjectName());
this.setProjectVersion(info.getTargetProjectVersion());
this.setBasePath(info.getBuildRootDir());
this.setComputerOS(info.getComputerOS());
this.setJvmVersion(info.getJVM());
}
//endregion
//region Attributes
/** Constant <code>Version</code> */
public static final Integer Version = 0;
public static Integer issueCounter = 0;
public static String projectName;
public static String projectVersion;
public static String basePath;
public static String computerOS;
public static String jvmVersion;
//endregion
//region Getters/Setters
public static Integer getVersion() {
return Version;
}
public static String getProjectName() {
return projectName;
}
public static void setProjectName(String projectName) {
CSVMapper.projectName = projectName;
}
public static String getProjectVersion() {
return projectVersion;
}
public static void setProjectVersion(String projectVersion) {
CSVMapper.projectVersion = projectVersion;
}
public static String getBasePath() {
return basePath;
}
public static void setBasePath(String basePath) {
CSVMapper.basePath = basePath;
}
public static String getComputerOS() {
return computerOS;
}
public static void setComputerOS(String computerOS) {
CSVMapper.computerOS = computerOS;
}
public static String getJvmVersion() {
return jvmVersion;
}
public static void setJvmVersion(String jvmVersion) {
CSVMapper.jvmVersion = jvmVersion;
}
public static Integer getIssueCounter() {
return issueCounter;
}
public static String addIssueCounter() {
return String.valueOf(issueCounter++);
}
public static void setIssueCounter(Integer issueCounter) {
CSVMapper.issueCounter = issueCounter;
}
//endregion
//region UnMarshallers
public String writeHeader() {
CustomStringBuilder headerLine = new CustomStringBuilder();
headerLine.add("ProjectName");
headerLine.add("ProjectVersion");
headerLine.add("FullPath");
headerLine.add("ComputerOs");
headerLine.add("JVMVersion");
headerLine.add("IssueId");
headerLine.add("IssueMessage");
headerLine.add("IssueDescription");
headerLine.add("IssueRuleNumber");
headerLine.add("IssueRuleDescription");
headerLine.add("CWEId");
headerLine.add("IssueSeverity");
headerLine.append("IssueFullPath");
return headerLine.toString();
}
public String writeIssue(AnalysisIssue issue) {
CustomStringBuilder issueLine = new CustomStringBuilder();
issueLine.add(this.getProjectName());
issueLine.add(this.getProjectVersion());
issueLine.add(this.getBasePath());
issueLine.add(this.getComputerOS());
issueLine.add(this.getJvmVersion());
issueLine.add(this.addIssueCounter());
issueLine.add(issue.getInfo());
issueLine.add(issue.getRule().getDesc());
issueLine.add(issue.getRule().getRuleId());
issueLine.add(issue.getRule().getDesc());
issueLine.add(issue.getRule().getCweId()[0]);
issueLine.add(1);
issueLine.append(issue.getFullPathName());
return issueLine.toString();
}
//endregion
//region Utils
/** A custom class to handle all of the csv escaping */
public class CustomStringBuilder {
private StringBuilder writer = new StringBuilder();
public void append(Object value) {
writer.append(StringEscapeUtils.escapeCsv(String.valueOf(value)));
}
public void add(Object value) {
writer.append(value).append(",");
}
@Override
public String toString() {
return writer.toString();
}
}
//endregion
}
| 4,163 | 24.546012 | 72 | java |
cryptoguard | cryptoguard-master/src/main/java/frontEnd/MessagingSystem/routing/outputStructures/common/Default.java | /* Licensed under GPL-3.0 */
package frontEnd.MessagingSystem.routing.outputStructures.common;
import frontEnd.MessagingSystem.AnalysisIssue;
import frontEnd.MessagingSystem.AnalysisLocation;
import frontEnd.MessagingSystem.routing.EnvironmentInformation;
import frontEnd.MessagingSystem.routing.structure.Default.Issue;
import frontEnd.MessagingSystem.routing.structure.Default.Location;
import frontEnd.MessagingSystem.routing.structure.Default.Report;
import frontEnd.MessagingSystem.routing.structure.Default.Target;
import rule.engine.EngineType;
import util.Utils;
/**
* Default class.
*
* @author franceme Created on 4/23/19.
* @version 03.07.01
* @since 03.04.08
* <p>{Description Here}
*/
public class Default {
//region Attributes
/** Constant <code>Version</code> */
public static final Integer Version = 3;
//endregion
//region UnMarshallers
/**
* mapper.
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
* @return a {@link frontEnd.MessagingSystem.routing.structure.Default.Report} object.
*/
public static Report mapper(EnvironmentInformation info) {
Report report = new Report();
report.setDateTime(info.getAssessmentStartTime());
report.setProjectName(Utils.projectName);
report.setProjectVersion(Utils.projectVersion);
report.setSchemaVersion(Version);
report.setUUID(info.getUUID());
return report;
}
/**
* mapper.
*
* @param report a {@link frontEnd.MessagingSystem.routing.structure.Default.Report} object.
* @return a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
*/
public static EnvironmentInformation mapper(Report report) {
EnvironmentInformation info = new EnvironmentInformation();
info.setAssessmentStartTime(report.getDateTime());
info.setTargetProjectName(report.getProjectName());
info.setTargetProjectVersion(report.getProjectVersion());
info.setUUID(report.getUUID());
info.setPackageRootDir(report.getTarget().getFullPath());
info.setPackageName(report.getTarget().getProjectName());
info.setTargetProjectName(report.getTarget().getProjectName());
info.setSourceType(mapper(report.getTarget().getType()));
info.setIsGradle(mapper(report.getTarget()));
info.setRawCommand(report.getTarget().getRawCommand());
info.getSource().addAll(report.getTarget().getTargetSources());
return info;
}
/**
* mapper.
*
* @param info a {@link frontEnd.MessagingSystem.routing.EnvironmentInformation} object.
* @param computerOS a {@link java.lang.String} object.
* @param jvmInfo a {@link java.lang.String} object.
* @return a {@link frontEnd.MessagingSystem.routing.structure.Default.Target} object.
*/
public static Target mapper(EnvironmentInformation info, String computerOS, String jvmInfo) {
Target target = new Target();
target.setComputerOS(computerOS);
target.setFullPath(info.getPackageRootDir());
target.setJVMVersion(jvmInfo);
target.setProjectName(
info.getTargetProjectName() == null ? info.getPackageName() : info.getTargetProjectName());
target.setType(mapper(info.getSourceType()));
if (info.getSourceType().equals(EngineType.DIR))
target.setProjectType(mapper(info.getIsGradle()));
target.setProjectVersion(info.getTargetProjectVersion());
target.setPropertiesFilePath(info.getPropertiesFile());
target.setRawCommand(info.getRawCommand());
target.setTargetSources(info.getSource());
return target;
}
/**
* mapper.
*
* @param type a {@link rule.engine.EngineType} object.
* @return a {@link frontEnd.MessagingSystem.routing.structure.Default.Target.Type} object.
*/
public static Target.Type mapper(EngineType type) {
switch (type) {
case APK:
return Target.Type.APK;
case DIR:
return Target.Type.SOURCE;
case JAR:
return Target.Type.JAR;
case JAVAFILES:
return Target.Type.JAVA;
case CLASSFILES:
return Target.Type.CLASS;
}
return Target.Type.JAR;
}
/**
* mapper.
*
* @param type a {@link frontEnd.MessagingSystem.routing.structure.Default.Target.Type} object.
* @return a {@link rule.engine.EngineType} object.
*/
public static EngineType mapper(Target.Type type) {
switch (type) {
case APK:
return EngineType.APK;
case JAR:
return EngineType.JAR;
case JAVA:
return EngineType.JAVAFILES;
case CLASS:
return EngineType.CLASSFILES;
case SOURCE:
return EngineType.DIR;
}
return EngineType.JAR;
}
/**
* mapper.
*
* @param isGradle a {@link java.lang.Boolean} object.
* @return a {@link frontEnd.MessagingSystem.routing.structure.Default.Target.ProjectType} object.
*/
public static Target.ProjectType mapper(Boolean isGradle) {
if (isGradle) return Target.ProjectType.GRADLE;
else return Target.ProjectType.MAVEN;
}
/**
* mapper.
*
* @param target a {@link frontEnd.MessagingSystem.routing.structure.Default.Target} object.
* @return a {@link java.lang.Boolean} object.
*/
public static Boolean mapper(Target target) {
return target.getProjectType().equals(Target.ProjectType.GRADLE);
}
/**
* mapper.
*
* @param oldIssue a {@link frontEnd.MessagingSystem.AnalysisIssue} object.
* @param id a {@link java.lang.Integer} object.
* @return a {@link frontEnd.MessagingSystem.routing.structure.Default.Issue} object.
*/
public static Issue mapper(AnalysisIssue oldIssue, Integer id) {
Issue issue = new Issue();
issue.setId(String.valueOf(id));
issue.setFullPath(oldIssue.getFullPathName());
Location loc = new Location();
if (!oldIssue.getLocations().isEmpty()) loc = mapper(oldIssue.getLocations().get(0));
loc.setClassName(oldIssue.getClassName());
loc.setMethodName(oldIssue.getMethods().peek().toString());
issue.setMessage(oldIssue.getInfo());
issue.setRuleNumber(oldIssue.getRuleId());
issue.setRuleDesc(oldIssue.getRule().getDesc());
issue.setCWEId(oldIssue.getRule().getCweId()[0]);
issue.setDescription(oldIssue.getRule().getDesc());
issue.setSeverity("1");
return issue;
}
/**
* mapper.
*
* @param oldIssue a {@link frontEnd.MessagingSystem.routing.structure.Default.Issue} object.
* @return a {@link frontEnd.MessagingSystem.AnalysisIssue} object.
*/
public static AnalysisIssue mapper(Issue oldIssue) {
AnalysisIssue issue = new AnalysisIssue(oldIssue.getRuleNumber());
issue.setFullPathName(oldIssue.getFullPath());
issue.setClassName(oldIssue.getLocation().getClassName());
issue.addMethod(oldIssue.getLocation().getMethodName(), mapper(oldIssue.getLocation()));
issue.setInfo(oldIssue.getMessage());
return issue;
}
/**
* mapper.
*
* @param oldLoc a {@link frontEnd.MessagingSystem.AnalysisLocation} object.
* @return a {@link frontEnd.MessagingSystem.routing.structure.Default.Location} object.
*/
public static Location mapper(AnalysisLocation oldLoc) {
Location loc = new Location();
if (oldLoc.getColStart() != null) loc.setStartColumn(oldLoc.getColStart());
if (oldLoc.getColEnd() != null) loc.setEndColumn(oldLoc.getColEnd());
if (oldLoc.getLineStart() != null) loc.setStartLine(oldLoc.getLineStart());
if (oldLoc.getLineEnd() != null) loc.setEndLine(oldLoc.getLineEnd());
return loc;
}
/**
* mapper.
*
* @param oldLoc a {@link frontEnd.MessagingSystem.routing.structure.Default.Location} object.
* @return a {@link frontEnd.MessagingSystem.AnalysisLocation} object.
*/
public static AnalysisLocation mapper(Location oldLoc) {
AnalysisLocation loc =
new AnalysisLocation((int) oldLoc.getStartLine(), (int) oldLoc.getEndLine());
loc.setColStart(((int) oldLoc.getStartColumn()));
loc.setColEnd(((int) oldLoc.getEndColumn()));
return loc;
}
//endregion
//region Common Methods
//endregion
}
| 8,054 | 30.837945 | 100 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.