Exploit Etherleak flaw
426393
def etherleak(target, **kargs):
    """"""
    return srp(Ether() / ARP(pdst=target),
               prn=lambda s_r: conf.padding_layer in s_r[1] and hexstr(s_r[1][conf.padding_layer].load),  # noqa: E501
               filter="arp", **kargs)
325765
def decrypt(source, dest=None, passphrase=None):
    """"""
    if not os.path.exists(source):
        raise CryptoritoError("Encrypted file %s not found" % source)

    cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
           passphrase_file(passphrase)]

    if dest:
        cmd.append(["--output", dest])

    cmd.append([source])
    stderr_output(flatten(cmd))
    return True
745084
def obfuscate_ip(ip):
    
    if is_valid_ipv4(ip):
        res = "0x%s" % "".join(hex(int(x))[2:] for x in ip.split("."))
    else:
        raise ValueError('Invalid IP value %r' % ip)
    assert is_obfuscated_ip(res),  '%r obfuscation error' % res
    return res
275414
function extractReadableKeys (dir, options) {
  const pwd = options.input
  prompt.start()
  prompt.get(promptSchema, (err, { password }) => {
    const key = fs.readFileSync(path.join(pwd, dir, 'sign_key'))
    const pubKey = fs.readFileSync(path.join(pwd, dir, 'sign_key.pub'))

    const decrypted = Crypto.decryptPrivateKey(password, key)

    const privateHex = Buffer.from(decrypted).toString('hex')
    const decryptedPub = Crypto.decryptPubKey(password, pubKey)

    console.log(`Private key (hex): ${privateHex}`)
    console.log(`Public key (base check): ak_${Crypto.encodeBase58Check(decryptedPub)}`)
    console.log(`Public key (hex): ${decryptedPub.toString('hex')}`)
  })
}
1015591
ByteBuffer encryptChunk(ByteBuffer cleartextChunk, long chunkNumber, byte[] headerNonce, SecretKey fileKey) {
		try {
			// nonce:
			byte[] nonce = new byte[NONCE_SIZE];
			random.nextBytes(nonce);

			// payload:
			final Cipher cipher = CipherSupplier.AES_CTR.forEncryption(fileKey, new IvParameterSpec(nonce));
			final ByteBuffer outBuf = ByteBuffer.allocate(NONCE_SIZE + cipher.getOutputSize(cleartextChunk.remaining()) + MAC_SIZE);
			outBuf.put(nonce);
			int bytesEncrypted = cipher.doFinal(cleartextChunk, outBuf);

			// mac:
			final ByteBuffer ciphertextBuf = outBuf.asReadOnlyBuffer();
			ciphertextBuf.position(NONCE_SIZE).limit(NONCE_SIZE + bytesEncrypted);
			byte[] authenticationCode = calcChunkMac(macKey, headerNonce, chunkNumber, nonce, ciphertextBuf);
			assert authenticationCode.length == MAC_SIZE;
			outBuf.put(authenticationCode);

			// flip and return:
			outBuf.flip();
			return outBuf;
		} catch (ShortBufferException e) {
			throw new IllegalStateException("Buffer allocated for reported output size apparently not big enough.", e);
		} catch (IllegalBlockSizeException | BadPaddingException e) {
			throw new IllegalStateException("Unexpected exception for CTR ciphers.", e);
		}
	}
601255
def fixup_prngs():
    
    s = os.urandom(256 // 8)
    random.seed(s)
    if 'ssl' in sys.modules:
        sys.modules['ssl'].RAND_add(s, 75.0)
624004
def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None,
            region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        plaintext = conn.decrypt(
            ciphertext_blob,
            encryption_context=encryption_context,
            grant_tokens=grant_tokens
        )
        r['plaintext'] = plaintext['Plaintext']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r
47314
function blockEncrypt(input, inOffset, sessionKey) {

        if (input &&
          sessionKey &&
          utils.isAnArray(sessionKey) &&
          utils.isAnArray(input)) {

          input = new Uint8Array(input);
          var sBox = sessionKey[0]
            , sKey = sessionKey[1]

            /*eslint-disable no-plusplus*/
            , x0 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24

            , x1 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24

            , x2 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24

            , x3 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24
            /*eslint-enable no-plusplus*/

            , t0
            , t1
            , k = ROUND_SUBKEYS
            , R = 0;

          x0 ^= sKey[INPUT_WHITEN];
          x1 ^= sKey[INPUT_WHITEN + 1];
          x2 ^= sKey[INPUT_WHITEN + 2];
          x3 ^= sKey[INPUT_WHITEN + 3];
          for (R = 0; R < ROUNDS; R += 2) {

            t0 = fe32(sBox, x0, 0);
            t1 = fe32(sBox, x1, 3);
            /*eslint-disable no-plusplus*/
            x2 ^= t0 + t1 + sKey[k++];
            /*eslint-enable no-plusplus*/
            x2 = x2 >>> 1 | x2 << 31;
            x3 = x3 << 1 | x3 >>> 31;
            /*eslint-disable no-plusplus*/
            x3 ^= t0 + 2 * t1 + sKey[k++];
            /*eslint-enable no-plusplus*/

            t0 = fe32(sBox, x2, 0);
            t1 = fe32(sBox, x3, 3);
            /*eslint-disable no-plusplus*/
            x0 ^= t0 + t1 + sKey[k++];
            /*eslint-enable no-plusplus*/
            x0 = x0 >>> 1 | x0 << 31;
            x1 = x1 << 1 | x1 >>> 31;
            /*eslint-disable no-plusplus*/
            x1 ^= t0 + 2 * t1 + sKey[k++];
            /*eslint-enable no-plusplus*/
          }

          x2 ^= sKey[OUTPUT_WHITEN];
          x3 ^= sKey[OUTPUT_WHITEN + 1];
          x0 ^= sKey[OUTPUT_WHITEN + 2];
          x1 ^= sKey[OUTPUT_WHITEN + 3];

          return new Uint8Array([x2, x2 >>> 8, x2 >>> 16, x2 >>> 24,
             x3, x3 >>> 8, x3 >>> 16, x3 >>> 24,
             x0, x0 >>> 8, x0 >>> 16, x0 >>> 24,
             x1, x1 >>> 8, x1 >>> 16, x1 >>> 24]);
        }

        throw 'input block is not an array or sessionKey is incorrect';
      }
529764
def cracked(self):
        
        logging.info("Cracking message: {0}".format(self.message))
        entropy_values = {}
        attempt_cache = {}
        message = self.message
        for i in range(25):
            self.message = message
            self.offset = i * -1
            logging.debug("Attempting crack with offset: "
                          "{0}".format(self.offset))
            test_cipher = self.cipher()
            logging.debug("Attempting plaintext: {0}".format(test_cipher))
            entropy_values[i] = self.calculate_entropy(test_cipher)
            attempt_cache[i] = test_cipher

        sorted_by_entropy = sorted(entropy_values, key=entropy_values.get)
        self.offset = sorted_by_entropy[0] * -1
        cracked_text = attempt_cache[sorted_by_entropy[0]]
        self.message = cracked_text

        logging.debug("Entropy scores: {0}".format(entropy_values))
        logging.debug("Lowest entropy score: "
                      "{0}".format(str(entropy_values[sorted_by_entropy[0]])))
        logging.debug("Most likely offset: {0}".format(self.offset))
        logging.debug("Most likely message: {0}".format(cracked_text))

        return cracked_text
1308177
def work(self):
        
        self.do_print = True
        if self.args.old:
            self.switch_fingerprint_method(True)

        ret = self.process_inputs()

        if self.args.dump:
            self.dump(ret)

        logger.info('### SUMMARY ####################')
        logger.info('Records tested: %s' % self.tested)
        logger.info('.. PEM certs: . . . %s' % self.num_pem_certs)
        logger.info('.. DER certs: . . . %s' % self.num_der_certs)
        logger.info('.. RSA key files: . %s' % self.num_rsa_keys)
        logger.info('.. PGP master keys: %s' % self.num_pgp_masters)
        logger.info('.. PGP total keys:  %s' % self.num_pgp_total)
        logger.info('.. SSH keys:  . . . %s' % self.num_ssh)
        logger.info('.. APK keys:  . . . %s' % self.num_apk)
        logger.info('.. JSON keys: . . . %s' % self.num_json)
        logger.info('.. LDIFF certs: . . %s' % self.num_ldiff_cert)
        logger.info('.. JKS certs: . . . %s' % self.num_jks_cert)
        logger.info('.. PKCS7: . . . . . %s' % self.num_pkcs7_cert)
        logger.debug('. Total RSA keys . %s  (# of keys RSA extracted & analyzed)' % self.num_rsa)
        if self.found > 0:
            logger.info('Fingerprinted keys found: %s' % self.found)
            logger.info('WARNING: Potential vulnerability')
        else:
            logger.info('No fingerprinted keys found (OK)')
        logger.info('################################')
100596
function Bugout(identifier, opts) {
  // TODO: option to pass shared secret to encrypt swarm traffic
  if (identifier && typeof(identifier) == "object") {
    opts = identifier;
    identifier = null;
  }
  var opts = opts || {};
  if (!(this instanceof Bugout)) return new Bugout(identifier, opts);
  
  var trackeropts = opts.tracker || {};
  trackeropts.getAnnounceOpts = trackeropts.getAnnounceOpts || function() { return {numwant: 4}; };
  if (opts.iceServers) {
    trackeropts.rtcConfig = {iceServers: opts.iceServers};
  }
  this.announce = opts.announce || ["wss://hub.bugout.link", "wss://tracker.openwebtorrent.com", "wss://tracker.btorrent.xyz"];
  this.wt = opts.wt || new WebTorrent({tracker: trackeropts});
  this.nacl = nacl;
  
  if (opts["seed"]) {
    this.seed = opts["seed"];
  } else {
    this.seed = this.encodeseed(nacl.randomBytes(32));
  }

  this.timeout = opts["timeout"] || PEERTIMEOUT;
  this.keyPair = opts["keyPair"] || nacl.sign.keyPair.fromSeed(Uint8Array.from(bs58check.decode(this.seed)).slice(2));
  // ephemeral encryption key only used for this session
  this.keyPairEncrypt = nacl.box.keyPair();

  this.pk = bs58.encode(Buffer.from(this.keyPair.publicKey));
  this.ek = bs58.encode(Buffer.from(this.keyPairEncrypt.publicKey));
  
  this.identifier = identifier || this.address();
  this.peers = {}; // list of peers seen recently: address -> pk, ek, timestamp
  this.seen = {}; // messages we've seen recently: hash -> timestamp
  this.lastwirecount = null;

  // rpc api functions and pending callback functions
  this.api = {};
  this.callbacks = {};
  this.serveraddress = null;
  this.heartbeattimer = null;
  
  debug("address", this.address());
  debug("identifier", this.identifier);
  debug("public key", this.pk);
  debug("encryption key", this.ek);
  
  if (typeof(File) == "object") {
    var blob = new File([this.identifier], this.identifier);
  } else {
    var blob = new Buffer.from(this.identifier);
    blob.name = this.identifier;
  }
  var torrent = this.wt.seed(blob, {"name": this.identifier, "announce": this.announce}, partial(function(bugout, torrent) {
    debug("torrent", bugout.identifier, torrent);
    bugout.emit("torrent", bugout.identifier, torrent);
    if (torrent.discovery.tracker) {
      torrent.discovery.tracker.on("update", function(update) { bugout.emit("tracker", bugout.identifier, update); });
    }
    torrent.discovery.on("trackerAnnounce", function() {
      bugout.emit("announce", bugout.identifier);
      bugout.connections();
    });
  }, this));
  torrent.on("wire", partial(attach, this, this.identifier));
  this.torrent = torrent;

  if (opts.heartbeat) {
    this.heartbeat(opts.heartbeat);
  }
}
145519
function exitHandler(options, err) {
  if (err) {
    if (err.stack) {
      console.error(err.stack);
    } else {
      console.error(err.toString());
    }
  }
	if (whitelistedVulnerabilities.length > 0) {
        logger.info(colors.bold.yellow("Filtering the following vulnerabilities"));
        logger.info(colors.bold.yellow('=================================================='));
        for (var i = 0; i < whitelistedVulnerabilities.length; i++) {
        	var detail = whitelistedVulnerabilities[i];
          logger.info(`${colors.bold.blue(detail['title'])} affected versions: ${colors.red(detail['package'])} ${colors.red(detail['versions'])}`);
          logger.info(`${detail['description']}`);
          logger.info(colors.bold("ID") + ": " + detail.id);
          if (detail.whitelistedPaths) {
            detail.whitelistedPaths.forEach(function(path) {
              logger.info(colors.bold("Ignored Path") + ": " + path);
            })
          }
          logger.info(colors.bold.yellow('=================================================='));
        };
	}

  logger.info('');
  logger.info('Audited dependencies: ' + actualAudits +
            ', Vulnerable: ' + colors.bold.red(vulnerabilityCount) +
            ', Ignored: ' + whitelistedVulnerabilities.length);

    if(config.get('report')) {
        var filtered = whitelistedVulnerabilities.length;
        mkdirp('reports');
        if (JUnit[0] != '<') { // This is a hack in case this gets called twice
        	// Convert to XML
            JUnit = jsontoxml(JUnit);
        }
        var dom = new DOMParser().parseFromString(JUnit);
        dom.documentElement.setAttribute('name', `auditjs.security.${programPackage.split('.')[0]}`);
        dom.documentElement.setAttribute('errors', 0);
        dom.documentElement.setAttribute('tests', expectedAudits);
        dom.documentElement.setAttribute('package', 'test');
        dom.documentElement.setAttribute('id', '');
        dom.documentElement.setAttribute('skipped', filtered);
        dom.documentElement.setAttribute('failures', vulnerabilityCount);
        JUnit = new XMLSerializer().serializeToString(dom);
        logger.info( `Wrote JUnit report to reports/${output}`);
        fs.writeFileSync('reports/' + output, `<?xml version="1.0" encoding="UTF-8"?>\n${JUnit}`);
    }

    if (config.get('suppressExitError')) {
      process.exit(0);
    } else {
      process.exit(vulnerabilityCount);
    }
}
765494
def wrap_insecure_channel(insecure_channel_func, tracer=None):
    """"""
    def call(*args, **kwargs):
        channel = insecure_channel_func(*args, **kwargs)

        try:
            target = kwargs.get('target')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap insecure channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call
744286
def stupid_hack(most=10, wait=None):
    """"""

    # Stupid Hack For Public Cloud so it is not overwhelmed with API requests.
    if wait is not None:
        time.sleep(wait)
    else:
        time.sleep(random.randrange(1, most))
988752
def ssh_capture(ip, command)
      retval = ""
      configure_ssh_command(ip, command) do |ch, success|
        return "" unless success

        ch.on_data do |ch, data|
          retval << data
        end

        ch.on_request("exit-status") do |ch, data|
          return retval
        end
      end

      return retval
    end
231824
def check_obfuscated_ip (self):
        """"""
        # check if self.host can be an IP address
        # check for obfuscated IP address
        if iputil.is_obfuscated_ip(self.host):
            ips = iputil.resolve_host(self.host)
            if ips:
                self.host = ips[0]
                self.add_warning(
                   _("URL %(url)s has obfuscated IP address %(ip)s") % \
                   {"url": self.base_url, "ip": ips[0]},
                          tag=WARN_URL_OBFUSCATED_IP)
644305
def _trapped_signals(self, client):
    """"""
    signal_handler = PailgunClientSignalHandler(
      client,
      timeout=self._bootstrap_options.for_global_scope().pantsd_pailgun_quit_timeout)
    with ExceptionSink.trapped_signals(signal_handler):
      yield