/// <summary>Converts an attribute into a specific type if a parser exists /// for it, otherwise stuffs it into a generic Attribute object.</summary> public static Attribute Parse(MemBlock data) { if (4 > data.Length) { throw new Exception("Poorly formed packet"); } ushort type = (ushort)NumberSerializer.ReadShort(data, 0); ushort length = (ushort)NumberSerializer.ReadShort(data, 2); if (4 + length > data.Length) { throw new Exception("Poorly formed packet"); } MemBlock att_data = MemBlock.Reference(data, 4, length); AttributeType attype = (AttributeType)type; if (attype == AttributeType.MappedAddress || attype == AttributeType.ResponseAddress || attype == AttributeType.ChangeAddress || attype == AttributeType.SourceAddress) { return(new AttributeAddress(attype, att_data)); } switch (attype) { default: return(new Attribute(attype, att_data)); } }
/* * Start sending packets */ public void Run() { byte[] buf = new byte[UInt16.MaxValue]; Random ran_obj = new Random(); for (int counter = 0; counter < count; counter++) { try { int size = ran_obj.Next(4, Int16.MaxValue); ran_obj.NextBytes(buf); NumberSerializer.WriteInt(counter, buf, 0); MemBlock cp = MemBlock.Copy(buf, 0, Math.Max(4, counter)); lock (_sync) { _sent_blocks[cp] = counter; } _e.Send(cp); Thread.Sleep(10); Console.WriteLine("Sending Packet #: " + counter); } catch (Exception x) { Console.WriteLine("send: {0} caused exception: {1}", counter, x); break; } } //Let all the responses get back Thread.Sleep(5000); Check(); _e.Close(); }
/// <summary>Change in either local or remote IDs, time to update the /// header to match.</summary> protected void UpdateHeader() { byte[] header = new byte[8]; NumberSerializer.WriteInt(_local_id, header, SOURCE_OFFSET); NumberSerializer.WriteInt(_remote_id, header, DESTINATION_OFFSET); _header = MemBlock.Reference(header); }
public IcmpPacket(Types type, short id, short seq_num) { Type = type; Identifier = id; SequenceNumber = seq_num; Code = (byte)0; byte[] msg = new byte[64]; Random rand = new Random(); rand.NextBytes(msg); msg[0] = (byte)type; msg[1] = Code; msg[2] = (byte)0; msg[3] = (byte)0; NumberSerializer.WriteShort(Identifier, msg, 4); NumberSerializer.WriteShort(SequenceNumber, msg, 6); short checksum = (short)IPPacket.GenerateChecksum(MemBlock.Reference(msg)); NumberSerializer.WriteShort(checksum, msg, 2); _icpacket = MemBlock.Reference(msg); _packet = MemBlock.Reference(msg); }
protected void SendControlPacket(EndPoint end, int remoteid, int localid, ControlCode c, object state) { using (MemoryStream ms = new MemoryStream()) { NumberSerializer.WriteInt((int)c, ms); if (c == ControlCode.EdgeDataAnnounce) { UdpEdge e = (UdpEdge)_id_ht[localid]; if ((e != null) && (e.RemoteID == remoteid)) { Hashtable t = new Hashtable(); t["RemoteTA"] = e.RemoteTA.ToString(); t["LocalTA"] = e.LocalTA.ToString(); AdrConverter.Serialize(t, ms); } else { if (ProtocolLog.UdpEdge.Enabled) { ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format( "Problem sending EdgeData: EndPoint: {0}, remoteid: {1}, " + "localid: {2}, Edge: {3}", end, remoteid, localid, e)); } } } _send_queue.Enqueue(new UdpMessage(localid, ~remoteid, MemBlock.Reference(ms.ToArray()), end)); if (ProtocolLog.UdpEdge.Enabled) { ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format( "Sending control {1} to: {0}", end, c)); } } }
public void HandleData(MemBlock b, ISender return_path, object state) { //Read the header: uint crc32 = (uint)NumberSerializer.ReadInt(b, 0); int id = NumberSerializer.ReadInt(b, 4); ushort block = (ushort)NumberSerializer.ReadShort(b, 8); MemBlock data = b.Slice(10); var cachekey = new Triple <uint, int, ushort>(crc32, id, block); MemBlock packet = null; lock (_sync) { if (false == _fragments.Contains(cachekey)) { //This is a new block: _fragments.Add(cachekey, data); var fc_key = new Pair <uint, int>(crc32, id); Fragments this_fc; if (false == _frag_count.TryGetValue(fc_key, out this_fc)) { this_fc = new Fragments(); _frag_count.Add(fc_key, this_fc); } if (this_fc.AddBlock(block)) { //We have all of them, decode and clean up: packet = DecodeAndClear(crc32, id, (ushort)this_fc.Total); } } } if (null != packet) { Handle(packet, new FragmentingSender(DEFAULT_SIZE, return_path)); } }
protected void SendThread() { byte[] buffer = new byte[8 + Int16.MaxValue]; bool timedout = false; while (_running == 1) { UdpMessage to_send = _send_queue.Dequeue(-1, out timedout); if (to_send == null) { break; } NumberSerializer.WriteInt(to_send.LocalID, buffer, 0); NumberSerializer.WriteInt(to_send.RemoteID, buffer, 4); try { int length = to_send.Data.CopyTo(buffer, 8); _s.SendTo(buffer, 8 + length, SocketFlags.None, to_send.Dst); } catch (SocketException x) { if ((1 == _running) && ProtocolLog.UdpEdge.Enabled) { ProtocolLog.Write(ProtocolLog.UdpEdge, x.ToString()); } } } }
/// <summary>Constructor for a TunnelEdge, RemoteID == -1 for out bound.</summary> public TunnelEdge(IEdgeSendHandler send_handler, TunnelTransportAddress local_ta, TunnelTransportAddress remote_ta, IForwarderSelector ias, List <Connection> overlap, int remote_id) : base(send_handler, remote_id != -1) { _remote_id = remote_id; lock (_rand) { LocalID = _rand.Next(); } byte[] bid = new byte[8]; NumberSerializer.WriteInt(LocalID, bid, 0); NumberSerializer.WriteInt(_remote_id, bid, 4); _mid = MemBlock.Reference(bid); _local_ta = local_ta; _remote_ta = remote_ta; _tunnels = new List <Connection>(overlap); _ias = ias; _ias.Update(_tunnels); AHHeader ahh = new AHHeader(1, 20, local_ta.Target, remote_ta.Target, AHHeader.Options.Exact); ICopyable header = new CopyList(PType.Protocol.AH, ahh, PType.Protocol.Tunneling); Header = MemBlock.Copy(header); }
/// <summary>Parse a revocation message.</summary> public UserRevocationMessage(Certificate cacert, MemBlock data) { _data = data; int pos = 0; int length = 0; Username = AdrConverter.Deserialize(data, pos, out length) as string; pos += length; // Random number to reduce likelihood of malicious duplication of messages NumberSerializer.ReadInt(data, pos); pos += 4; // Verify that there is a date contained therein, perhaps we should verify the time new DateTime(NumberSerializer.ReadLong(data, pos)); pos += 8; Signature = new byte[data.Length - pos]; data.Slice(pos).CopyTo(Signature, 0); // hash the data SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); Hash = sha1.ComputeHash(data, 0, data.Length - Signature.Length); if (!cacert.PublicKey.VerifyHash(Hash, CryptoConfig.MapNameToOID("SHA1"), Signature)) { throw new Exception("Invalid UserRevocationMessage signature"); } }
/** * Abandon any attempts to get requests for the given ID. * @throw Exception if handler is not the original handler for this Request */ public void StopRequest(int request_id, IReplyHandler handler) { RequestState rs = null; lock ( _sync ) { if (!_req_state_table.TryTake(request_id, out rs)) { rs = null; } } if (rs != null) { /* * Send an ack for this reply: */ byte[] ack_payload = new byte[5]; ack_payload[0] = (byte)ReqrepType.ReplyAck; NumberSerializer.WriteInt(request_id, ack_payload, 1); ICopyable data = new CopyList(_prefix, MemBlock.Reference(ack_payload)); foreach (ISender ret_path in rs.Repliers) { try { //Try to send an ack, but if we can't, oh well... ret_path.Send(data); } catch { } } } }
public AHHeader(short hops, short ttl, Address source, Address dest, ushort options) { //Make the header part: byte[] header = new byte[LENGTH]; int offset = 0; //Write hops: NumberSerializer.WriteShort(hops, header, offset); Hops = hops; offset += 2; NumberSerializer.WriteShort(ttl, header, offset); Ttl = ttl; offset += 2; _src = source; offset += source.CopyTo(header, offset); _dest = dest; offset += dest.CopyTo(header, offset); Opts = options; NumberSerializer.WriteShort((short)options, header, offset); offset += 2; _data = MemBlock.Reference(header, 0, offset); }
/// <summary>Continues a broadcast to the overlay.</summary> public BroadcastSender(StructuredNode node, AHAddress source, AHAddress from, AHAddress to, int forwarders, int hops) { Node = node; Source = source; From = from; To = to; _distance_sorter = new AbsoluteDistanceComparer(node.Address as AHAddress); _address_sorter = new LeftDistanceComparer(node.Address as AHAddress); Forwarders = forwarders; Hops = hops; byte[] hops_data = new byte[4]; NumberSerializer.WriteInt(hops, hops_data, 0); _hops = MemBlock.Reference(hops_data); if (forwarders == DEFAULT_FORWARDERS) { _forwarders = DEFAULT_FORWARDERS_MB; } else { byte[] def = new byte[4]; NumberSerializer.WriteInt(forwarders, def, 0); _forwarders = MemBlock.Reference(def); } }
public int CopyTo(byte[] dest, int off) { _data.CopyTo(dest, off); //The Hops is not neccesarily correct in _data NumberSerializer.WriteShort(Hops, dest, off); return(LENGTH); }
/** * This is either a request or response. Look up the handler * for it, and pass the packet to the handler */ public void HandleData(MemBlock p, ISender from, object state) { //Is it a request or reply? ReqrepType rt = (ReqrepType)((byte)p[0]); int idnum = NumberSerializer.ReadInt(p, 1); MemBlock rest = p.Slice(5); //Skip the type and the id if (rt == ReqrepType.Request || rt == ReqrepType.LossyRequest) { HandleRequest(rt, idnum, rest, from); } else if (rt == ReqrepType.Reply) { HandleReply(rt, idnum, rest, from); } else if (rt == ReqrepType.ReplyAck) { HandleReplyAck(rt, idnum, rest, from); } else if (rt == ReqrepType.RequestAck) { HandleRequestAck(rt, idnum, rest, from); } else if (rt == ReqrepType.Error) { HandleError(rt, idnum, rest, from); } }
public DirectionalAddress(DirectionalAddress.Direction bearing) : base() { byte[] buffer = new byte[MemSize]; NumberSerializer.WriteInt((int)bearing, buffer, 0); SetClass(buffer, this.Class); _dir = bearing; _buffer = MemBlock.Reference(buffer, 0, MemSize); }
/// <summary>Parse an Attribute.</summary> public Attribute(MemBlock data) { Data = data; Type = (AttributeType)((ushort)NumberSerializer.ReadShort(data, 0)); ushort length = (ushort)NumberSerializer.ReadShort(data, 2); Value = MemBlock.Reference(data, 4, length); }
/** * Return a random AHAddress initialized from the given rng */ public AHAddress(RandomNumberGenerator rng) { byte[] buffer = new byte[MemSize]; rng.GetBytes(buffer); SetClass(buffer, this.Class); _buffer = MemBlock.Reference(buffer, 0, MemSize); _prefix = (uint)NumberSerializer.ReadInt(_buffer, 0); }
/// <summary>Parses web data and updates the revoked users hashtable if /// successful</summary> protected void UpdateRl(byte[] data) { // message is length (4) + date (8) + data (variable) + hash (~20) int length = data.Length; if (length < 12) { throw new Exception("No data? Didn't get enough data..."); } length = NumberSerializer.ReadInt(data, 0); DateTime date = new DateTime(NumberSerializer.ReadLong(data, 4)); // warn the user that this is an old revocation list, maybe there is an attack if (date < DateTime.UtcNow.AddHours(-24)) { ProtocolLog.WriteIf(IpopLog.GroupVPN, "Revocation list is over 24 hours old"); } // Weird, data length is longer than the data we got if (length > data.Length - 12) { throw new Exception("Missing data? Didn't get enough data..."); } // hash the data and verify the signature SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(data, 4, length); byte[] signature = new byte[data.Length - 4 - length]; Array.Copy(data, 4 + length, signature, 0, signature.Length); if (!_ca_cert.PublicKey.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature)) { throw new Exception("Invalid signature!"); } // convert the data to an array list as it was sent to us MemBlock mem = MemBlock.Reference(data, 12, length - 8); ArrayList rl = AdrConverter.Deserialize(mem) as ArrayList; if (rl == null) { throw new Exception("Data wasn't a list..."); } // convert it into a hashtable for O(1) look ups Hashtable ht = new Hashtable(); foreach (string username in rl) { ht[username] = true; } Interlocked.Exchange(ref _revoked_users, ht); }
protected ICopyable MakeRequest(ReqrepType rt, int next_rep, ICopyable data) { byte[] header = new byte[5]; header[0] = (byte)rt; NumberSerializer.WriteInt(next_rep, header, 1); MemBlock mb_header = MemBlock.Reference(header); return(new CopyList(_prefix, mb_header, data)); }
/// <summary>Parse an AttributeAddress.</summary> public AttributeAddress(AttributeType type, MemBlock data) : base(type, data) { Family = (FamilyType)data[1]; Port = (ushort)NumberSerializer.ReadShort(data, 2); byte[] addr = new byte[data.Length - 4]; data.Slice(4).CopyTo(addr, 0); IP = new IPAddress(addr); }
/** * Read the address out of the buffer This makes a copy * and calls Parse on the copy. This is a "convienience" method. * @throw ParseException if the buffer is not a valid address */ static public Address Parse(MemBlock mb) { //Read some of the least significant bytes out, //AHAddress all have last bit 0, so we skip the last byte which //will have less entropy ushort idx = (ushort)NumberSerializer.ReadShort(mb, Address.MemSize - 3); Address a = _mb_cache[idx]; if (a != null) { if (a.ToMemBlock().Equals(mb)) { return(a); } } //Else we need to read the address and put it in the cache try { if (2 * mb.Length < mb.ReferencedBufferLength) { /* * This MemBlock is much smaller than the array * we are referencing, don't keep the big one * in scope, instead make a copy */ mb = MemBlock.Copy((ICopyable)mb); } int add_class = Address.ClassOf(mb); switch (add_class) { case AHAddress.ClassValue: a = new AHAddress(mb); break; case DirectionalAddress.ClassValue: a = new DirectionalAddress(mb); break; default: a = null; throw new ParseException("Unknown Address Class: " + add_class + ", buffer:" + mb.ToString()); } //Cache this result: _mb_cache[idx] = a; return(a); } catch (ArgumentOutOfRangeException ex) { throw new ParseException("Address too short: " + mb.ToString(), ex); } catch (ArgumentException ex) { throw new ParseException("Could not parse: " + mb.ToString(), ex); } }
protected byte[] CalculateCookie(int uid) { byte[] cookie_base = _cookie; byte[] cookie_full = new byte[cookie_base.Length + 4]; cookie_base.CopyTo(cookie_full, 0); NumberSerializer.WriteInt(uid, cookie_full, cookie_base.Length); SHA1 sha = new SHA1CryptoServiceProvider(); return(sha.ComputeHash(cookie_full)); }
public AHAddress(BigInteger big_int) : base(big_int) { if (ClassOf(_buffer) != this.Class) { throw new System. ArgumentException("Class of address is not my class: ", this.ToString()); } _prefix = (uint)NumberSerializer.ReadInt(_buffer, 0); }
/// <summary>Create a new Attribute.</summary> public Attribute(AttributeType type, MemBlock value) { Type = type; Value = value; byte[] data = new byte[4 + value.Length]; NumberSerializer.WriteUShort((ushort)type, data, 0); NumberSerializer.WriteUShort((ushort)value.Length, data, 2); value.CopyTo(data, 4); Data = MemBlock.Reference(data); }
public void SendAck() { _have_sent_ack = 1; byte[] header = new byte[5]; header[0] = (byte)ReqrepType.RequestAck; NumberSerializer.WriteInt(RequestID, header, 1); MemBlock mb_header = MemBlock.Reference(header); ReturnPath.Send(new CopyList(_prefix, mb_header)); }
public void HandleData(MemBlock p, ISender edge, object state) { try { int num = NumberSerializer.ReadInt(p, 0); Console.WriteLine("Got packet number: {0}", num); edge.Send(p); } catch (Exception x) { Console.WriteLine("Server got exception on send: {0}", x); } }
///<summary>Decrypts the packet given a SymmetricEncryption returning true ///if it was able to decrypt it.</summary> public bool Decrypt(SymmetricEncryption se) { byte[] decrypted = se.DecryptData(_encrypted_data); int pos = 0; int data_len = NumberSerializer.ReadInt(decrypted, pos); pos += 4; _data = MemBlock.Reference(decrypted, pos, data_len); pos += data_len; _signature = MemBlock.Reference(decrypted, pos, decrypted.Length - pos); return(true); }
/// <summary>We take in an object, take its hash code, concatenate it /// to our cookie, then sha hash the resulting value, creating the remote /// cookie.</summary> public MemBlock CalculateCookie(object o) { int hash = o.GetHashCode(); byte[] data = new byte[4 + _cookie.Length]; _cookie.CopyTo(data, 0); NumberSerializer.WriteInt(hash, data, _cookie.Length); HashAlgorithm sha1 = new SHA1CryptoServiceProvider(); byte[] cookie = sha1.ComputeHash(data); return(MemBlock.Reference(cookie)); }
public DirectionalAddress(MemBlock mb) { if (ClassOf(mb) != this.Class) { throw new System. ArgumentException ("This is not an AHAddress (Class 124) : ", this.ToString()); } _buffer = mb; _dir = (Direction)NumberSerializer.ReadInt(mb, 0); }
/// Simulator != thread-safe! protected static Address SimulatorCache(Address a) { int idx = NumberSerializer.ReadInt(a.ToMemBlock(), 0); Address tmp = _cache.GetValue(idx); if (a.Equals(tmp)) { return(tmp); } _cache.Replace(idx, a); return(a); }