/// <summary> /// Returns the header portion of the given data /// </summary> /// <param name="data"></param> /// <returns></returns> private static Tuple <byte, byte, byte, UInt32> _read_header(byte[] data) { var Result = StructConverter.Unpack("<BBBI", data.SubArray(":7")); byte data_type = (byte)Result[0]; byte buffer_id = (byte)Result[1]; byte seq_no = (byte)Result[2]; UInt32 frame_size = (UInt32)Result[3]; return(Tuple.Create(data_type, buffer_id, seq_no, frame_size)); }
/// <summary> /// Create an ACK packet based on the given header information /// </summary> /// <param name="data_type"></param> /// <param name="buffer_id"></param> /// <param name="seq_no"></param> /// <returns></returns> private byte[] _create_ack_packet(byte data_type, byte buffer_id, byte seq_no) { Debug.Assert(data_type == (byte)SumoConstantsCustom.ARNETWORKAL_FRAME_TYPE.ARNETWORKAL_FRAME_TYPE_DATA_WITH_ACK); // The payload of an ACK frame is the sequence no. of the data frame byte payload = seq_no; // The buffer id is 128 + base_id byte[] buffer = StructConverter.Pack("<BBBI", new object[] { (byte)SumoConstantsCustom.ARNETWORKAL_FRAME_TYPE.ARNETWORKAL_FRAME_TYPE_ACK, (byte)buffer_id + 128, (byte)0, (byte)8 }); //"<BBBI" return(buffer.Concat(new byte[] { payload }).ToArray()); }
public void TestBufferFromTacTest() { // This packet was generated by tactest using the following command line: // .\tactest.exe -s 10.5.33.145 -k abcdefghijklmnopqrstuvwxyz123456 -u booger -p Test123 -type CHAP -challenge 1234567890123456789012345678901234567890123456789 var packet = new byte[] { 0xc1, 0x01, 0x01, 0x04, 0x6c, 0x94, 0xc2, 0xa8, 0x00, 0x00, 0x00, 0x50, 0x24, 0xa1, 0x35, 0x2a, 0xf9, 0x9b, 0x78, 0xd9, 0xc1, 0xb1, 0xbe, 0xcd, 0x24, 0x95, 0xab, 0x48, 0x2f, 0xae, 0xdd, 0x1a, 0x8a, 0xf0, 0x54, 0xa3, 0x28, 0x2b, 0x97, 0x12, 0x9e, 0x28, 0x58, 0x12, 0xff, 0x80, 0x7d, 0xff, 0x7b, 0x73, 0xe5, 0xc6, 0xe7, 0xb7, 0xb1, 0x28, 0xb6, 0x1b, 0x94, 0xbb, 0x4f, 0x19, 0xeb, 0x4d, 0xf7, 0x01, 0x0a, 0x1c, 0x06, 0x15, 0x06, 0xc8, 0x23, 0x15, 0xba, 0x23, 0xc7, 0xce, 0x4b, 0x38, 0xf2, 0xa7, 0xa1, 0x70, 0x16, 0x9a, 0x30, 0xca, 0x17, 0x10, 0xb1, 0x5a }; var user = "******"; var password = "******".ToSecureString(); var sharedSecret = "abcdefghijklmnopqrstuvwxyz123456".ToSecureString(); var header = StructConverter.BytesToStruct <TacacsHeader>(packet); Assert.Equal(0xc1, header.Version); Assert.Equal(TacacsFlags.SingleConnectionMode, header.Flags); Assert.Equal(0x50, header.Length); Assert.Equal(0x01, header.SequenceNumber); Assert.Equal(TacacsType.Authentication, header.Type); // Can't validate session number, because it is random var payload = packet.Skip(12).Take(packet.Length - 12).ToArray(); var pseudoPad = TacacsPlusProtocol.GetPseudoPad(header, header.Length, sharedSecret); Assert.Equal(payload.Length, pseudoPad.Length); var plainPayload = TacacsPlusProtocol.XorPseudoPad(payload, pseudoPad); var authenticationHeader = StructConverter.BytesToStruct <TacacsAuthenticationRequestHeader>(plainPayload); Assert.Equal(TacacsAuthenticationType.Chap, authenticationHeader.AuthenticationType); Assert.Equal(TacacsAction.Login, authenticationHeader.Action); Assert.Equal(TacacsAuthenticationService.None, authenticationHeader.Service); Assert.Equal(user.Length, authenticationHeader.UserLength); Assert.Equal(0x00, authenticationHeader.PortLength); Assert.Equal(0x00, authenticationHeader.RemoteLength); Assert.Equal(0x42, authenticationHeader.DataLength); var authenticationData = plainPayload.Skip(plainPayload.Length - 0x42).Take(0x42).ToArray(); var identifier = authenticationData.Take(1).ToArray(); var hardcodedChallenge = Encoding.ASCII.GetBytes("1234567890123456789012345678901234567890123456789"); var challenge = authenticationData.Skip(1).Take(hardcodedChallenge.Length).ToArray(); Assert.Equal(hardcodedChallenge, challenge); // Verify that we can generate the same response var calculated = Chap.GetResponse(identifier, challenge, password); var expected = authenticationData.Skip(1 + challenge.Length).ToArray(); Assert.Equal(expected, calculated); }
public Player(int id, Tcp connect, ShipInfo[] info, BaseProjectilesController projController) { structConverter = new StructConverter(); shipsInfo = info; Id = id; connection = connect; projectilesController = projController; shipController = new ShipController(historySize); Initialize(); }
public MainWindow() { InitializeComponent(); Load(); DataContext = SettingsViewModel; StructConverter = new StructConverter(SettingsViewModel.KnownTypes); InterfaceConverter = new InterfaceConverter(SettingsViewModel.KnownTypes); ConverterBox.ItemsSource = Enum.GetValues(typeof(KnownConverter)); ConverterBox.SelectedIndex = 0; }
/// <summary> /// Returns true if the given command is a pcmd command and false otherwise /// </summary> /// <param name="cmd"></param> /// <returns></returns> public static bool _is_pcmd(byte[] cmd) { // BBHBbb: Header (7) + payload (7) if (cmd.Length != 14) { return(false); } var Result = StructConverter.Unpack("<BBH", cmd.SubArray("7:11")); return(Tuple.Create <byte, byte, UInt16>((byte)Result[0], (byte)Result[1], (UInt16)Result[2]).Equals(Tuple.Create <byte, byte, UInt16>(3, 0, 0))); }
public NetController(ShipsController shipsController) { converter = new StructConverter(); EndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(serverAddress), sendingPort); tcp = new Tcp(serverEndPoint); udp = new ConnectedUdp(tcp.LocalEndPoint, serverEndPoint); this.shipsController = shipsController; shipControllers = new List <ShipController>(); sender = new Sender(udp); }
public static bool TryParse(string value, out AppWindowProperties props) { props = default(AppWindowProperties); if (string.IsNullOrEmpty(value) || !value.StartsWith(Prefix)) { return(false); } props = StructConverter.FromString <AppWindowProperties>(value.Substring(8)); return(true); }
/// <summary> /// Immediately Send Audio Stream /// </summary> /// <param name="AudioData"></param> public void SendAudioFrame(byte[] AudioData) { if (isConnected) { if (AudioData != null) { byte[] AudioHeader = StructConverter.Pack("<QHHI", new Object[] { (UInt64)0, (UInt32)0, (UInt32)0, (UInt16)0 }); byte[] AudioFrame = AudioHeader.Concat(AudioData).ToArray(); this.Send(AudioFrame); } } }
public static byte[] CreatePacket(TacacsHeader header, byte[] data, SecureString sharedSecret) { header.Length = data.Length; var packetLength = 12 /* tacacs header len */ + data.Length; var packet = new byte[packetLength]; var headerBuf = StructConverter.StructToBytes(header); Buffer.BlockCopy(headerBuf, 0, packet, 0, 12); var obfuscated = ObfuscateData(header, data, sharedSecret); Buffer.BlockCopy(obfuscated, 0, packet, 12, obfuscated.Length); return(packet); }
protected void OutputContentChanged() { try { var structConverter = new StructConverter(SettingsViewModel.KnownTypes); var converted = structConverter.Parse(Input.Text, false); Output.Text = structConverter.PrintParsedClass(converted, "projName", string.Empty, string.Empty); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// /// </summary> public void QueryTopInfo() { MsgHeader mh = new MsgHeader(); //参数赋值 mh.MsgID = ConstIDs.O_TDMOM_TOP_INFO_REQ; mh.puData = 0; mh.DataLen = 0; mh.MsgLen = (uint)Marshal.SizeOf(mh); byte[] res_mh = StructConverter.StructToBytes(mh); }
public IPEResult Package(IPEInfo param) { var peHeader = new PEHeader { Characteristics = param.Characteristics, Architecture = param.Architecture, CreationTimePOSIX = (uint)((DateTimeOffset)param.TimeStamp).ToUnixTimeSeconds(), NumberOfSections = param.NumberOfSections, Magic = BitConverter.ToUInt32(Encoding.ASCII.GetBytes("PE\0\0")), OptionalHeaderSize = (ushort)Marshal.SizeOf <PE32PlusOptionalHeader>() }; return(new PEResult(StructConverter.GetBytes(peHeader))); }
public bool TryGetSharedData(string key, out object data) { Contract.NotEmpty(key, nameof(key)); CheckExistence(); using (var converter = new StringConverter()) { var argument = Rage.Entity.Entity_GetVariable(NativePointer, converter.StringToPointer(key)); data = ArgumentConverter.ConvertToObject(StructConverter.PointerToStruct <ArgumentData>(argument)); return(data != null); } }
public byte[] Bytes(bool includeLength) { var sid = GetRandomBytes(8); var ts = (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var packet = new List <object>(); packet.Add(1); packet.Add(ts); packet.Add((byte)(7 << 3)); foreach (var s in sid) { packet.Add(s); } packet.Add((byte)0); packet.Add(0); using (var h = new HMACSHA1()) { h.Key = _key.Take(h.HashSize / 8).ToArray(); var data = StructConverter.Pack(packet.ToArray(), false); var hash = h.ComputeHash(data); var result = new List <object>(); result.Add((byte)(7 << 3)); foreach (var s in sid) { result.Add(s); } foreach (var hs in hash) { result.Add(hs); } result.Add(1); result.Add(ts); result.Add((byte)0); result.Add(0); var bytes = StructConverter.Pack(result.ToArray(), false); if (!includeLength) { return(bytes); } var length = StructConverter.Pack(new object[] { (ushort)bytes.Length }, false); return(length.Concat(bytes).ToArray()); } }
private void ExportCPPButton_Click(object sender, EventArgs e) { using (SaveFileDialog fileDialog = new SaveFileDialog() { DefaultExt = "cpp", Filter = "C++ source files|*.cpp", InitialDirectory = Environment.CurrentDirectory, RestoreDirectory = true }) { fileDialog.InitialDirectory = modFolder; fileDialog.FileName = Path.GetFileNameWithoutExtension(fileName); if (fileDialog.ShowDialog(this) == DialogResult.OK) { StructConverter.ExportCPP(iniData, itemsToExport, fileDialog.FileName); } } }
protected bool SendNoParam(CommandTuple cmdTuple) { SequenceCounter["SEND_WITH_ACK"] = (SequenceCounter["SEND_WITH_ACK"] + 1) % 256; // ReSharper disable once StringLiteralTypo const string fmt = "<BBBIBBH"; Command cmd = new Command(); cmd.InsertData((byte)DataTypesByName["DATA_WITH_ACK"]); cmd.InsertData((byte)BufferIds["SEND_WITH_ACK"]); cmd.InsertData((byte)SequenceCounter["SEND_WITH_ACK"]); cmd.InsertData((uint)StructConverter.PacketSize(fmt)); cmd.InsertTuple(cmdTuple); return(SendCommandAck(cmd.Export(fmt), SequenceCounter["SEND_WITH_ACK"])); }
public Room(int listeningPort, int sendingPort, ShipInfo[] ships) { physicsController = new PhysicsController(); Body.SetPhysicsController(physicsController); shipsInfo = ships; roomClosed = false; lastId = 0; bots = new List <ShipController>(); players = new List <Player>(); structConverter = new StructConverter(); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, listeningPort); udp = new Udp(localEndPoint); connector = new TcpConnector(localEndPoint); projectilesController = new BaseProjectilesController(100); }
protected void AckPacket(int bufferId, int packetId) { // ReSharper disable once StringLiteralTypo const string fmt = "<BBBIB"; int newBufferId = (bufferId + 128) % 256; Command cmd = new Command { SequenceId = newBufferId }; cmd.InsertData((byte)DataTypesByName["ACK"]); cmd.InsertData((byte)newBufferId); cmd.InsertData((byte)cmd.SequenceId); cmd.InsertData((uint)StructConverter.PacketSize(fmt)); cmd.InsertData((byte)packetId); SafeSend(cmd.Export(fmt)); }
// ReSharper disable once IdentifierTypo protected bool SendSinglePcmd(CommandTuple cmdTuple, CommandParam cmdParam) { SequenceCounter["SEND_NO_ACK"] = (SequenceCounter["SEND_NO_ACK"] + 1) % 256; // ReSharper disable once StringLiteralTypo string fmt = "<BBBIBBH" + cmdParam.Format(); Command cmd = new Command(); cmd.InsertData((byte)DataTypesByName["DATA_NO_ACK"]); cmd.InsertData((byte)BufferIds["SEND_NO_ACK"]); cmd.InsertData((byte)SequenceCounter["SEND_NO_ACK"]); cmd.InsertData((uint)StructConverter.PacketSize(fmt)); cmd.InsertTuple(cmdTuple); cmd.InsertParam(cmdParam); return(SafeSend(cmd.Export(fmt))); }
private byte[] ValidateResponseAndGetPayload(byte[] responsePacket) { var responseHeader = StructConverter.BytesToStruct <TacacsHeader>(responsePacket); if (responseHeader.Version != 0xc1) { throw new Exception($"Unexpected response header version: 0x{responseHeader.Version:X}"); } if (responseHeader.Flags != TacacsFlags.Encrypted) { throw new Exception($"Unexpected response header flags: 0x{responseHeader.Flags:X}"); } if (responseHeader.SequenceNumber % 2 != 0) { throw new Exception($"Response header sequence number should be odd: 0x{responseHeader.SequenceNumber:X}"); } return(GetResponsePayload(responseHeader, responsePacket)); }
private void ExportINIButton_Click(object sender, EventArgs e) { bool autoSaveSuccess = false; string autoSaveName = ""; bool preferAutoSave = true; // make this configurable later. if (preferAutoSave) { if (modFolder != null && modFolder.Length > 0) { // try doing auto-export Directory.CreateDirectory(modFolder); if (Directory.Exists(modFolder)) { autoSaveSuccess = true; autoSaveName = Path.Combine(modFolder, fileName); } } } if (autoSaveSuccess) { StructConverter.ExportINI(iniData, itemsToExport, autoSaveName); MessageBox.Show("Export Complete!"); Hide(); } else { using (SaveFileDialog fileDialog = new SaveFileDialog() { DefaultExt = "ini", Filter = "INI files|*.ini", InitialDirectory = modFolder, RestoreDirectory = true }) { fileDialog.InitialDirectory = modFolder; fileDialog.FileName = fileName; if (fileDialog.ShowDialog(this) == DialogResult.OK) { StructConverter.ExportINI(iniData, itemsToExport, fileDialog.FileName); } } } }
public static byte[] GetAuthenticationData(TacacsAuthenticationService service, string user, SecureString password) { var userBuf = user.GetUserBuffer(); var authenticationHeader = new TacacsAuthenticationRequestHeader() { Action = TacacsAction.Login, PrivilegeLevel = 0x01, AuthenticationType = TacacsAuthenticationType.Chap, Service = service, UserLength = ((byte)userBuf.Length), PortLength = ((byte)ClientPortName.Length), RemoteLength = 0x00, // optional -- excluded DataLength = 0x42 // 66 bytes -- big challenge }; var identifier = new byte[1]; Rng.GetBytes(identifier, 0, 1); //var challenge = new byte[49]; //Rng.GetBytes(challenge, 0, 32); var challenge = Encoding.ASCII.GetBytes("1234567890123456789012345678901234567890123456789"); var response = GetResponse(identifier, challenge, password); var data = new byte[1 /* identifier */ + 49 /* challenge */ + 16 /* response */]; Buffer.BlockCopy(identifier, 0, data, 0, 1); Buffer.BlockCopy(challenge, 0, data, 1, 49); Buffer.BlockCopy(response, 0, data, 50, 16); var authenticationDataLength = 8 /* header */ + userBuf.Length + ClientPortName.Length + 0 /* remote */ + 66 /* CHAP length */; var authenticationData = new byte[authenticationDataLength]; var headerBuf = StructConverter.StructToBytes(authenticationHeader); Buffer.BlockCopy(headerBuf, 0, authenticationData, 0, 8); Buffer.BlockCopy(userBuf, 0, authenticationData, 8, userBuf.Length); Buffer.BlockCopy(ClientPortName, 0, authenticationData, 8 + userBuf.Length, ClientPortName.Length); Buffer.BlockCopy(data, 0, authenticationData, 8 + userBuf.Length + ClientPortName.Length, data.Length); return(authenticationData); }
/// <summary> /// /// </summary> public void SendIpInfo() { MsgHeader mh = new MsgHeader(); //参数赋值 mh.MsgID = ConstIDs.O_TDMOM_IP_PORT_CFG; mh.puData = 0; mh.DataLen = 0; mh.MsgLen = (uint)Marshal.SizeOf(mh); byte[] res_mh = StructConverter.StructToBytes(mh); IpPortCFCStruct ips = new IpPortCFCStruct(); byte[] strbytes = System.Text.Encoding.Unicode.GetBytes(_configService.ConfigInfos.TermialIP); Buffer.BlockCopy(strbytes, 0, ips.IpAddr, 0, ips.IpAddr.Length > strbytes.Length ? strbytes.Length : ips.IpAddr.Length); ips.PortNum = (uint)_configService.ConfigInfos.TerminalPort; //发送 }
private PacketHeader GetPacketHeader(byte[] binaryData) { var packetHeader = new PacketHeader(); try { var chunkData = binaryData.Skip(0).Take(1).ToArray(); var data = StructConverter.Unpack("b", chunkData); packetHeader.PacketType = Convert.ToInt32(data[0]); chunkData = binaryData.Skip(1).Take(2).ToArray(); data = StructConverter.Unpack("h", chunkData); packetHeader.PacketSubtype = Convert.ToInt16(data[0]); chunkData = binaryData.Skip(3).Take(1).ToArray(); data = StructConverter.Unpack("b", chunkData); packetHeader.StreamId = Convert.ToInt32(data[0]); chunkData = binaryData.Skip(4).Take(8).ToArray(); data = StructConverter.Unpack("d", chunkData); packetHeader.StartTime = Convert.ToDouble(data[0]); chunkData = binaryData.Skip(12).Take(8).ToArray(); data = StructConverter.Unpack("d", chunkData); packetHeader.EndTime = Convert.ToDouble(data[0]); chunkData = binaryData.Skip(20).Take(4).ToArray(); data = StructConverter.Unpack("I", chunkData); packetHeader.PacketSize = Convert.ToUInt32(data[0]); chunkData = binaryData.Skip(24).Take(4).ToArray(); data = StructConverter.Unpack("I", chunkData); packetHeader.ParameterSize = Convert.ToUInt32(data[0]); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(packetHeader); }
protected void SendPong(byte[] data) { int byteSize = 4, totalByteSize = byteSize + data.Length; // ReSharper disable once StringLiteralTypo const string fmt = "<BBBI"; SequenceCounter["PONG"] = (SequenceCounter["PONG"] + 1) % 256; Command cmd = new Command(); cmd.InsertData((byte)DataTypesByName["DATA_NO_ACK"]); cmd.InsertData((byte)BufferIds["PONG"]); cmd.InsertData((byte)SequenceCounter["PONG"]); cmd.InsertData((uint)(StructConverter.PacketSize(fmt) + data.Length)); byte[] initCommand = cmd.Export(fmt); Array.Resize(ref initCommand, totalByteSize); data.CopyTo(initCommand, byteSize); SafeSend(initCommand); }
public bool Authenticate(TacacsAuthenticationType type, TacacsAuthenticationService service, string user, SecureString password) { if (string.IsNullOrEmpty(user)) { throw new ArgumentException("Must specify a valid user name", nameof(user)); } if (password == null) { throw new ArgumentException("Must specify a valid password", nameof(password)); } var requestPacket = TacacsPlusProtocol.GetAuthenticationPacket(type, service, user, password, _sharedSecret); var responsePacket = SendReceive(requestPacket); var responsePayload = ValidateResponseAndGetPayload(responsePacket); var authenticationReplyHeader = StructConverter.BytesToStruct <TacacsAuthenticationReplyHeader>(responsePayload); switch (authenticationReplyHeader.Status) { case TacacsAuthenticationStatus.Pass: return(true); case TacacsAuthenticationStatus.Fail: return(false); case TacacsAuthenticationStatus.Error: var serverMessage = Encoding.UTF8.GetString(responsePacket.Skip(6 /* Authentication Reply Header Size */) .Take(authenticationReplyHeader.ServerMessageLength).ToArray()); throw new Exception($"Server responded with an error: {serverMessage}"); default: throw new Exception($"Unexpected authentication status: {authenticationReplyHeader.Status}"); } }
/// <summary> /// /// </summary> public ArticleDetail() { SitecoreAddin.TagActiveDocument(); _sitecoreArticle = new SitecoreClient(); _documentCustomProperties = new DocumentCustomProperties(SitecoreAddin.ActiveDocument); _structConverter = new StructConverter(); ArticleDetails.ArticleNumber = _documentCustomProperties.ArticleNumber; InitializeComponent(); articleDetailsPageSelector.LinkToParent(this); articleStatusBar1.LinkToParent(this); if (!string.IsNullOrEmpty(_documentCustomProperties.ArticleNumber)) { articleStatusBar1.DisplayStatusBar(true, _documentCustomProperties.ArticleNumber); } else { articleStatusBar1.DisplayStatusBar(false, _documentCustomProperties.ArticleNumber); } if (this.articleDetailsPageSelector.pageArticleInformationControl._isCheckedOut) { articleStatusBar1.ChangeLockButtonStatus(LockStatus.Unlocked); } else { articleStatusBar1.ChangeLockButtonStatus(LockStatus.Locked); } articleDetailsPageSelector.InitializePages(); SitecoreUser.GetUser().ResetAuthenticatedSubscription(); SitecoreUser.GetUser().Authenticated += PopulateFieldsOnAuthentication; InitializeLogin(); }
private bool TryGetPosition(out WINDOWPLACEMENT placement) { try { placement = default(WINDOWPLACEMENT); using (var reader = new StreamReader(new IsolatedStorageFileStream(_storageFilePath, FileMode.OpenOrCreate, _store))) { var str = reader.ReadToEnd(); if (!string.IsNullOrEmpty(str)) { placement = StructConverter.FromString <WINDOWPLACEMENT>(str); return(true); } return(false); } } catch (Exception e) { Logger.Error("Error reading saved window position", e); placement = default(WINDOWPLACEMENT); return(false); } }
public TimeData GetTime() { return(StructConverter.PointerToStruct <TimeData>(Rage.World.World_GetTime(_nativePointer))); }