Example #1
0
 private void receivePing(Packet packet) {
   boolean ok = packet.verifySignature(_context, packet.getOptionalFrom(), null);
   if (!ok) {
     if (_log.shouldLog(Log.WARN)) {
       if (packet.getOptionalFrom() == null)
         _log.warn(
             "Ping with no from (flagged? " + packet.isFlagSet(Packet.FLAG_FROM_INCLUDED) + ")");
       else if (packet.getOptionalSignature() == null)
         _log.warn(
             "Ping with no signature (flagged? "
                 + packet.isFlagSet(Packet.FLAG_SIGNATURE_INCLUDED)
                 + ")");
       else
         _log.warn(
             "Forged ping, discard (from="
                 + packet.getOptionalFrom().calculateHash().toBase64()
                 + " sig="
                 + packet.getOptionalSignature().toBase64()
                 + ")");
     }
   } else {
     PacketLocal pong = new PacketLocal(_context, packet.getOptionalFrom());
     pong.setFlag(Packet.FLAG_ECHO, true);
     pong.setFlag(Packet.FLAG_SIGNATURE_INCLUDED, false);
     pong.setReceiveStreamId(packet.getSendStreamId());
     _manager.getPacketQueue().enqueue(pong);
   }
 }
Example #2
0
 /**
  * Non-SYN packets with a zero SendStreamID may also be queued here so that they don't get thrown
  * away while the SYN packet before it is queued.
  *
  * <p>Additional overload protection may be required here... We don't have a 3-way handshake, so
  * the SYN fully opens a connection. Does that make us more or less vulnerable to SYN flooding?
  */
 public void receiveNewSyn(Packet packet) {
   if (!_active) {
     if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) {
       if (_log.shouldLog(Log.WARN)) _log.warn("Dropping new SYN request, as we're not listening");
       sendReset(packet);
     } else {
       if (_log.shouldLog(Log.WARN)) _log.warn("Dropping non-SYN packet - not listening");
     }
     return;
   }
   if (_manager.wasRecentlyClosed(packet.getSendStreamId())) {
     if (_log.shouldLog(Log.WARN))
       _log.warn("Dropping packet for recently closed stream: " + packet);
     return;
   }
   if (_log.shouldLog(Log.INFO))
     _log.info("Receive new SYN: " + packet + ": timeout in " + _acceptTimeout);
   // also check if expiration of the head is long past for overload detection with peek() ?
   boolean success = _synQueue.offer(packet); // fail immediately if full
   if (success) {
     _context.simpleScheduler().addEvent(new TimeoutSyn(packet), _acceptTimeout);
   } else {
     if (_log.shouldLog(Log.WARN)) _log.warn("Dropping new SYN request, as the queue is full");
     if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) sendReset(packet);
   }
 }
Example #3
0
 /**
  * This sends a reset back to the place this packet came from. If the packet has no 'optional
  * from' or valid signature, this does nothing. This is not associated with a connection, so no
  * con stats are updated.
  */
 private void sendReset(Packet packet) {
   Destination from = packet.getOptionalFrom();
   if (from == null) return;
   boolean ok = packet.verifySignature(_context, from, null);
   if (!ok) {
     if (_log.shouldLog(Log.WARN))
       _log.warn("Can't send reset after recv spoofed packet: " + packet);
     return;
   }
   PacketLocal reply = new PacketLocal(_context, from);
   reply.setFlag(Packet.FLAG_RESET);
   reply.setFlag(Packet.FLAG_SIGNATURE_INCLUDED);
   reply.setSendStreamId(packet.getReceiveStreamId());
   reply.setReceiveStreamId(packet.getSendStreamId());
   reply.setOptionalFrom(_manager.getSession().getMyDestination());
   // this just sends the packet - no retries or whatnot
   _manager.getPacketQueue().enqueue(reply);
 }
Example #4
0
  void receivePacketDirect(Packet packet, boolean queueIfNoConn) {
    // if (_log.shouldLog(Log.DEBUG))
    //    _log.debug("packet received: " + packet);

    long sendId = packet.getSendStreamId();

    Connection con = (sendId > 0 ? _manager.getConnectionByInboundId(sendId) : null);
    if (con != null) {
      if (_log.shouldLog(Log.INFO))
        displayPacket(
            packet,
            "RECV",
            "wsize " + con.getOptions().getWindowSize() + " rto " + con.getOptions().getRTO());
      receiveKnownCon(con, packet);
    } else {
      receiveUnknownCon(packet, sendId, queueIfNoConn);
      displayPacket(packet, "UNKN", null);
    }
    // Don't log here, wait until we have the conn to make the dumps easier to follow
    // ((PacketLocal)packet).logTCPDump(true);
  }
Example #5
0
  private void receiveUnknownCon(Packet packet, long sendId, boolean queueIfNoConn) {
    if (packet.isFlagSet(Packet.FLAG_ECHO)) {
      if (packet.getSendStreamId() > 0) {
        if (_manager.answerPings()) receivePing(packet);
        else if (_log.shouldLog(Log.WARN))
          _log.warn("Dropping Echo packet on unknown con: " + packet);
      } else if (packet.getReceiveStreamId() > 0) {
        receivePong(packet);
      } else {
        if (_log.shouldLog(Log.WARN))
          _log.warn("Echo packet received with no stream IDs: " + packet);
      }
      packet.releasePayload();
    } else {
      if (_log.shouldLog(Log.WARN) && !packet.isFlagSet(Packet.FLAG_SYNCHRONIZE))
        _log.warn("Packet received on an unknown stream (and not an ECHO or SYN): " + packet);
      if (sendId <= 0) {
        Connection con = _manager.getConnectionByOutboundId(packet.getReceiveStreamId());
        if (con != null) {
          if ((con.getHighestAckedThrough() <= 5) && (packet.getSequenceNum() <= 5)) {
            if (_log.shouldLog(Log.WARN))
              _log.warn(
                  "Received additional packet w/o SendStreamID after the syn on "
                      + con
                      + ": "
                      + packet);
            receiveKnownCon(con, packet);
            return;
          } else {
            if (_log.shouldLog(Log.WARN))
              _log.warn(
                  "hrmph, received while ack of syn was in flight on "
                      + con
                      + ": "
                      + packet
                      + " acked: "
                      + con.getAckedPackets());
            // allow unlimited packets without a SendStreamID for now
            receiveKnownCon(con, packet);
            return;
          }
        }
      }

      if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) {
        // logTCPDump() will be called in ConnectionManager.receiveConnection(),
        // which is called by ConnectionHandler.receiveNewSyn(),
        // after we have a new conn, which makes the logging better.
        _manager.getConnectionHandler().receiveNewSyn(packet);
      } else if (queueIfNoConn) {
        // don't call logTCPDump() here, wait for it to find a conn

        // We can get here on the 2nd+ packet if the 1st (SYN) packet
        // is still on the _synQueue in the ConnectionHandler, and
        // ConnectionManager.receiveConnection() hasn't run yet to put
        // the StreamID on the getConnectionByOutboundId list.
        // Then the 2nd packet gets discarded and has to be retransmitted.
        //
        // We fix this by putting this packet on the syn queue too!
        // Then ConnectionHandler.accept() will check the connection list
        // and call receivePacket() above instead of receiveConnection().
        if (_log.shouldLog(Log.WARN)) {
          _log.warn("Packet belongs to no other cons, putting on the syn queue: " + packet);
        }
        if (_log.shouldLog(Log.DEBUG)) {
          StringBuilder buf = new StringBuilder(128);
          for (Connection con : _manager.listConnections()) {
            buf.append(con.toString()).append(" ");
          }
          _log.debug(
              "connections: "
                  + buf.toString()
                  + " sendId: "
                  + (sendId > 0 ? Packet.toId(sendId) : " unknown"));
        }
        // packet.releasePayload();
        _manager.getConnectionHandler().receiveNewSyn(packet);
      } else {
        // log it here, just before we kill it - dest will be unknown
        if (I2PSocketManagerFull.pcapWriter != null
            && _context.getBooleanProperty(I2PSocketManagerFull.PROP_PCAP)) packet.logTCPDump(null);
        // don't queue again (infinite loop!)
        sendReset(packet);
        packet.releasePayload();
      }
    }
  }
Example #6
0
  private void receiveKnownCon(Connection con, Packet packet) {
    // is this ok here or does it need to be below each packetHandler().receivePacket() ?
    if (I2PSocketManagerFull.pcapWriter != null
        && _context.getBooleanProperty(I2PSocketManagerFull.PROP_PCAP)) packet.logTCPDump(con);
    if (packet.isFlagSet(Packet.FLAG_ECHO)) {
      if (packet.getSendStreamId() > 0) {
        if (con.getOptions().getAnswerPings()) receivePing(packet);
        else if (_log.shouldLog(Log.WARN))
          _log.warn("Dropping Echo packet on existing con: " + packet);
      } else if (packet.getReceiveStreamId() > 0) {
        receivePong(packet);
      } else {
        if (_log.shouldLog(Log.WARN))
          _log.warn("Echo packet received with no stream IDs: " + packet);
      }
      packet.releasePayload();
      return;
    }

    // the packet is pointed at a stream ID we're receiving on
    if (isValidMatch(con.getSendStreamId(), packet.getReceiveStreamId())) {
      // the packet's receive stream ID also matches what we expect
      // if (_log.shouldLog(Log.DEBUG))
      //    _log.debug("receive valid: " + packet);
      try {
        con.getPacketHandler().receivePacket(packet, con);
      } catch (I2PException ie) {
        if (_log.shouldLog(Log.WARN)) _log.warn("Received forged packet for " + con, ie);
      }
    } else {
      if (packet.isFlagSet(Packet.FLAG_RESET)) {
        // refused
        if (_log.shouldLog(Log.DEBUG)) _log.debug("receive reset: " + packet);
        try {
          con.getPacketHandler().receivePacket(packet, con);
        } catch (I2PException ie) {
          if (_log.shouldLog(Log.WARN)) _log.warn("Received forged reset for " + con, ie);
        }
      } else {
        if ((con.getSendStreamId() <= 0)
            || (con.getSendStreamId() == packet.getReceiveStreamId())
            || (packet.getSequenceNum()
                <= ConnectionOptions.MIN_WINDOW_SIZE)) { // its in flight from the first batch
          long oldId = con.getSendStreamId();
          if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) {
            if (oldId <= 0) {
              // con fully established, w00t
              con.setSendStreamId(packet.getReceiveStreamId());
            } else if (oldId == packet.getReceiveStreamId()) {
              // ok, as expected...
            } else {
              if (_log.shouldLog(Log.WARN))
                _log.warn("Received a syn with the wrong IDs, con=" + con + " packet=" + packet);
              sendReset(packet);
              packet.releasePayload();
              return;
            }
          }

          try {
            con.getPacketHandler().receivePacket(packet, con);
          } catch (I2PException ie) {
            if (_log.shouldLog(Log.ERROR))
              _log.error("Received forged packet for " + con + "/" + oldId + ": " + packet, ie);
            con.setSendStreamId(oldId);
          }
        } else if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) {
          if (_log.shouldLog(Log.WARN))
            _log.warn("Receive a syn packet with the wrong IDs, sending reset: " + packet);
          sendReset(packet);
          packet.releasePayload();
        } else {
          if (!con.getResetSent()) {
            // someone is sending us a packet on the wrong stream
            // It isn't a SYN so it isn't likely to have a FROM to send a reset back to
            if (_log.shouldLog(Log.ERROR)) {
              StringBuilder buf = new StringBuilder(512);
              buf.append("Received a packet on the wrong stream: ");
              buf.append(packet);
              buf.append("\nthis connection:\n");
              buf.append(con);
              buf.append("\nall connections:");
              for (Connection cur : _manager.listConnections()) {
                buf.append('\n').append(cur);
              }
              _log.error(buf.toString(), new Exception("Wrong stream"));
            }
          }
          packet.releasePayload();
        }
      }
    }
  }