/// <summary> /// Waits until the connected client sends a SOCKS5 request. /// </summary> /// <returns>The SOCKS5 request sent by the client.</returns> /// <exception cref="Socks5Exception">The data sent by the client /// is not a valid SOCKS5 request.</exception> private SocksRequest WaitForRequest() { ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { byte[] bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp)bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } try { return(SocksRequest.Deserialize(b.ToArray())); } catch (Exception e) { throw new Socks5Exception("The request could not be serialized.", e); } }
private void fb_param_set(string[] fb_parm) { ByteBuilder bb = new ByteBuilder(); byte txLPF; byte fb_res1; byte fb_res2; try { txLPF = Convert.ToByte(fb_parm[0]); fb_res1 = Convert.ToByte(fb_parm[1]); fb_res2 = Convert.ToByte(fb_parm[2]); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } bb.Append(txLPF); bb.Append(fb_res1); bb.Append(fb_res2); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_FB_PARAM, bb.GetByteArray()))) { } }
private byte[] BuildSelectRcpPacket() { ByteBuilder bb = new ByteBuilder(); int discard; byte[] param = new byte[7]; param[0] = (byte) ((comboBoxSelTarget.SelectedIndex << 5) + (comboBoxSelAction.SelectedIndex << 2) + (comboBoxSelMemBank.SelectedIndex)); param[1] = 0; param[2] = 0; param[3] = (byte)((Convert.ToUInt16(tbSelPointer.Text, 16) & 0xFF00) >> 8); param[4] = (byte)((Convert.ToUInt16(tbSelPointer.Text, 16) & 0x00FF)); param[5] = byte.Parse(tbSelLength.Text); param[6] = 0; bb.Append(param); byte[] mask = HexEncoding.GetBytes(tbSelMask.Text, out discard); Array.Resize(ref mask, ((param[5] + 7) / 8)); if (mask.Length > 0) { bb.Append(mask); } return(bb.GetByteArray()); }
private void buttonUpdateTable_Click(object sender, EventArgs e) { m_aChannel = new byte[this.listViewEx1.Items.Count]; for (int i = 0; i < this.listViewEx1.Items.Count; i++) { try { m_aChannel[i] = byte.Parse(this.listViewEx1.Items[i].SubItems[1].Text); } catch { } } ByteBuilder bb = new ByteBuilder(); bb.Clear(); bb.Append((byte)this.GetChannelTable().Length); bb.Append(this.GetChannelTable()); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_HOPPING_TBL, bb.GetByteArray()))) { } bb.Clear(); }
/// <summary> /// Performs the specified SOCKS5 request. /// </summary> /// <param name="request">The SOCKS5 request to issue to the server.</param> /// <returns>The SOCKS5 reply sent by the server.</returns> /// <exception cref="ArgumentNullException">The request parameter is /// null.</exception> /// <exception cref="ObjectDisposedException">The object has been /// disposed.</exception> /// <exception cref="Socks5Exception">The request could not be performed. /// Consult the InnerException property of the Socks5Exception to learn /// the reason.</exception> public SocksReply Request(SocksRequest request) { AssertValid(); try { byte[] bytes = request.Serialize(); stream.Write(bytes, 0, bytes.Length); ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp)bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } return(SocksReply.Deserialize(b.ToArray())); } catch (Exception e) { throw new Socks5Exception("The request could not be performed.", e); } }
public void Parse(string axisName, string axis, ref byte[] dstAxis, ref int dimension) { string[] m = axis.Split(); bool error = false; string s; int i; dimension = 0; bb.Reset(); for (i = 0; i < m.Length; i++) { s = m[i].Trim(); if (s.Length > 0) { string[] h = s.Split(','); string k; int j; bb.Append((byte)h.Length); dimension++; for (j = 0; j < h.Length; j++) { k = h[j].Trim(); if (k.Length < 1) { Console.WriteLine("*** [" + name + "]:" + puzzleStart + ":" + axisName + " axis: garbage sequence on index " + (i + 1)); error = true; } else { try { byte v; v = (byte)int.Parse(k); if (v < 0 || v > 100) { throw new Exception(""); } bb.Append(v); } catch { Console.WriteLine("*** [" + name + "]:" + puzzleStart + ":" + axisName + " axis: garbage number (index " + (i + 1) + ")"); error = true; } } } } } if (error) { dstAxis = null; } else { dstAxis = bb.ToBytes(); } }
private void btnDownLoad_Click(object sender, EventArgs e) { byte[] msg = Encoding.ASCII.GetBytes(txtWifi.Text + (chkD.Checked ? '\n'.ToString() : "") + (chkA.Checked ? '\r'.ToString() : "")); ByteBuilder bb = new ByteBuilder(); bb.Append((byte)2); bb.Append(msg); if (!SystemPub.ADRcp.SendBytePkt(SystemPub.ADRcp.BuildCmdPacketByte(PassiveRcp.RCP_MSG_SENIOR_SET, PassiveRcp.RCP_CMD_WIFI_DOWNLOAD, bb.GetByteArray()))) { } }
private void button_WriteModulePowerTable_Click(object sender, EventArgs e) { ByteBuilder bb = new ByteBuilder(); for (int i = 0; i < temp_Estimate.Length; i++) { bb.Append(Convert.ToByte((temp_Estimate[i] >> 8) & 0xff)); bb.Append(Convert.ToByte(temp_Estimate[i] & 0xff)); } if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_MODULE_TABLE, bb.GetByteArray()))) { } }
private void SetFrequncyHopppingChannelTable(byte[] data) { int size = data[5]; if (size > data.Length - 9) { return; } ByteBuilder ba = new ByteBuilder(); for (int i = 6; i < size + 6; i++) { ba.Append(data[i]); } formChannelTable.SetChannel(ba.GetByteArray()); if (formChannelTable.isDisplayed) { } else { formChannelTable.ShowDialog(); } }
/// <summary> /// Serializes the instance into an array of bytes. /// </summary> /// <returns>An array of bytes representing the instance of the /// ClientGreeting class.</returns> public byte[] Serialize() { ByteBuilder b = new ByteBuilder() .Append(version) .Append((byte) methods.Count); foreach (AuthMethod m in Methods) b.Append((byte) m); return b.ToArray(); }
public byte[] EncodeMessage(byte[] buffer, int offset, int count) { lock (_sync) { var @sealed = new byte[count]; _sealing.ProcessBytes(buffer, offset, count, @sealed, 0); var concatHash = _signing.ComputeHash(_builder.Append(_clientSequence).Append(buffer, offset, count).ToArray()); _builder.Clear(); _sealing.ProcessBytes(concatHash, 0, _seal.Length, _seal, 0); var signed = _builder.Append(Ntlmv2Cipher.Version).Append(_seal).Append(_clientSequence).Append(@sealed).ToArray(); _builder.Clear(); _clientSequence++; return(signed); } }
private void buttonEepErase_Click(object sender, EventArgs e) { ByteBuilder bb = new ByteBuilder(); bb.Append(0xff); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_ERASE_FLASH, bb.GetByteArray()))) { } }
private void regUpdate() { ByteBuilder bb = new ByteBuilder(); bb.Append(0x01); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_UPDATE_FLASH, bb.GetByteArray()))) { } }
public void SetTxPower(float power) { ByteBuilder bb = new ByteBuilder(); bb.Append((UInt16)(power * 100)); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_TX_PWR, bb.GetByteArray()))) { } }
/// <summary> /// Serializes the instance into an array of bytes. /// </summary> /// <returns>An array of bytes representing the instance of the /// ClientGreeting class.</returns> public byte[] Serialize() { ByteBuilder b = new ByteBuilder() .Append(version) .Append((byte)methods.Count); foreach (AuthMethod m in Methods) { b.Append((byte)m); } return(b.ToArray()); }
private void SetModulePowerTable(byte[] data) { int size = data[5]; if (size > data.Length - 9) { return; } refModulePwr = new UInt16[(size >> 1)]; ByteBuilder ba = new ByteBuilder(); for (int i = 0; i < (size >> 1); i++) { refModulePwr[i] = Convert.ToUInt16(data[(i * 2) + 6] << 8); refModulePwr[i] += data[i * 2 + 7]; } FormPowerLevellTable formPowerLevelTable = new FormPowerLevellTable(); formPowerLevelTable.SetPowerLevel(refModulePwr, aCalOffsetTbl); if (formPowerLevelTable.ShowDialog() == DialogResult.OK) { refModulePwr = (UInt16[])formPowerLevelTable.APower.Clone(); ba.Clear(); ba.Append((byte)(refModulePwr.Length * 2)); for (int i = 0; i < refModulePwr.Length; i++) { ba.Append((UInt16)refModulePwr[i]); } if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_MODULE_PWR_TBL, ba.GetByteArray()))) { } } }
private byte[] BuildSelectRcpPacket(string target) { ByteBuilder bb = new ByteBuilder(); string[] temp = new string[0]; if (target != null) { temp = target.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); } byte[] mask = new byte[0]; if (target != null) { mask = new byte[temp.Length]; for (int i = 0; i < mask.Length; i++) { mask[i] = Convert.ToByte(temp[i], 16); } } byte[] param = new byte[7]; param[0] = 0x01; // Bank : EPC param[1] = 0x00; param[2] = 0x00; param[3] = 0x00; param[4] = 0x20; // Pointer : head of EPC param[5] = Convert.ToByte(temp.Length << 3); param[6] = 0; bb.Append(param); bb.Append(mask); return(bb.GetByteArray()); }
//public event RegistryUpdate_Result registryUpdate_result; private void button_UpdateNow_Click(object sender, EventArgs e) { //this.registryUpdate_result(true); ByteBuilder bb = new ByteBuilder(); bb.Append(0x01); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_UPDATE_FLASH, bb.GetByteArray()))) { } this.Close(); }
/// <summary> /// Performs the initial greeting. /// </summary> /// <exception cref="Socks5Exception">The client sent invalid data, or /// requires authentication.</exception> /// <exception cref="IOException">The stream could not be read, or the /// operation timed out.</exception> private void PerformGreeting() { ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { byte[] bytes = r.ReadBytes(2); b.Append(bytes); // The number of method-bytes following is contained in the second byte. b.Append(r.ReadBytes(bytes[1])); } ClientGreeting greeting = ClientGreeting.Deserialize(b.ToArray()); // We only accept an authentication method of 'none'. if (!greeting.Methods.Contains(AuthMethod.None)) { Dispose(); throw new Socks5Exception("Client requires authentication."); } // Send back our greeting response. var response = new ServerGreeting(AuthMethod.None).Serialize(); stream.Write(response, 0, response.Length); }
/// <summary> /// Creates a new "multi-precision integer" from the specified array /// of bytes. /// </summary> /// <param name="data">A big-endian sequence of bytes forming the /// integer value of the multi-precision integer.</param> public Mpi(byte[] data) { byte[] b = new byte[data.Length]; Array.Copy(data.Reverse().ToArray(), b, data.Length); ByteBuilder builder = new ByteBuilder().Append(b); // We append a null byte to the buffer which ensures the most // significant bit will never be set and the big integer value // always be positive. if (b.Last() != 0) { builder.Append(0); } Value = new BigInteger(builder.ToArray()); }
public int DecodeMessage(byte[] buffer, int offset, int count, byte[] output, int outOff) { lock (_sync) { _sealing.ProcessBytes(buffer, offset + MessageOffset, count - MessageOffset, output, outOff); _sealing.ProcessBytes(buffer, offset + SealOffset, _seal.Length, _seal, 0); var concatHash = _signing.ComputeHash(_builder.Append(buffer, SequenceOffset, 4).Append(output, outOff, count - MessageOffset).ToArray()); _builder.Clear(); if (!_seal.SequenceEqual(concatHash.Take(Ntlmv2Cipher.SealLength))) { throw new Exception("Server signature check failed"); } return(count - MessageOffset); } }
/// <summary> /// Reads an ASCII-string of the specified length from this instance. /// </summary> /// <param name="reader">Extension method for the BinaryReader class.</param> /// <param name="count">The number of bytes to read from the underlying /// stream.</param> /// <returns>A string decoded from the bytes read from the underlying /// stream using the ASCII character set.</returns> public static string ReadASCIIString(this BinaryReader reader, int count) { ByteBuilder builder = new ByteBuilder(); int read = 0; while (true) { if (read++ >= count) { break; } byte b = reader.ReadByte(); builder.Append(b); } return(Encoding.ASCII.GetString(builder.ToArray()).TrimEnd('\0')); }
// Handler that receives data if all the headers were not in the initial receive void HeaderBuilderHandler(ref SelectControl selectControl, Socket clientSocket, Buf safeBuffer) { int bytesReceived = clientSocket.Receive(safeBuffer.array); if (bytesReceived <= 0) { if (AppLayerProxy.Logger != null) { AppLayerProxy.Logger.WriteLine("{0} Closed ({1} bytes received but did not finish HTTP headers)", clientLogString, clientBuffer.contentLength); } selectControl.DisposeAndRemoveReceiveSocket(clientSocket); return; } clientBuffer.Append(safeBuffer.array, 0, (uint)bytesReceived); CheckForEndOfHeadersAndHandle(ref selectControl, clientSocket, clientBuffer.bytes, 0, clientBuffer.contentLength); }
private static byte[] Encode(byte[] bytes, Dictionary <byte, BitArray> bitTable) { ByteBuilder byteBuilder = new ByteBuilder(); List <byte> outputBytes = new List <byte>(bytes.Count()); foreach (var inputByte in bytes) { byteBuilder.Append(bitTable[inputByte]); while (byteBuilder.IsByteRedy()) { outputBytes.Add(byteBuilder.GetByte()); } } outputBytes.AddRange(byteBuilder.GetAllBytes()); return(outputBytes.ToArray()); }
public string ReadWord() { var b = new ByteBuilder(); while (CanRead) { byte c = Data[Position]; if (c == '\r' || c == '\n' || c == ':' || c == ',' || c == ']') { break; } b.Append(c); Position++; } return(b.ToString()); }
private void buttonSetTxPwr_Click(object sender, EventArgs e) { ByteBuilder bb = new ByteBuilder(); float power = 0f; try { power = (float)Convert.ToDouble((string)cbTxPwr.SelectedItem); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } bb.Append((UInt16)(power * 10)); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_MODULE_TX_PWR, bb.GetByteArray()))) { } }
private byte[] BuildSendLine(int address) { ByteBuilder bb = new ByteBuilder(); bb.Append((byte)RcpProtocol.PREAMBLE); bb.Append((byte)'W'); bb.Append((byte)(address >> 8)); bb.Append((byte)(address & 0x00FF)); for (int i = 0; i < 0x10; i++) { bb.Append(rawCode[address + i]); } bb.Append((byte)RcpProtocol.ENDMARK); bb.Append(CRCCalculator.Cal_CRC16(bb.GetByteArray())); return(bb.GetByteArray()); }
private void UpdateProcess() { bool bUpdateSuccess = false; int add = 0; int len = 0; if (m_nDownloadMode == DOWNLOAD_MODE_LEGACY) { len = PACKET_SIZE; } else { len = PACKET_EX_SIZE; } this.Invoke(new MethodInvoker(delegate() { progressBarUpdate.Maximum = m_nAddMax / len; })); System.Threading.Thread.Sleep(100); try { while (add < m_nAddMax) { byte[] byteSend; // = BuildSendLine(add); RxCheckCnt = 0; if (m_nDownloadMode == DOWNLOAD_MODE_LEGACY) { byteSend = BuildSendLine(add); } else { byteSend = BuildSendLineEx(add); } m_bReceived = false; if (!Sio.Instance.Send(byteSend)) { throw new Exception("Failure to send a packet"); } RxCheckTimer.Start(); while (!m_bReceived) { if (RxCheckCnt > 100) { throw new Exception("Time Out "); } } this.Invoke(new MethodInvoker(delegate() { progressBarUpdate.PerformStep(); })); //add = add + 0x10; add = add + len; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (add >= m_nAddMax) { ByteBuilder bb = new ByteBuilder(); bb.Append(0xbb); bb.Append(0x59); for (int i = 0; i < 19; i++) { bb.Append(0xff); } bb.Append(0x7e); bb.Append(0x00); bb.Append(0x00); bUpdateSuccess = true; } this.Invoke(new MethodInvoker(delegate() { progressBarUpdate.Value = 0; })); if (bUpdateSuccess) { MessageBox.Show("Update complete... Please reset your hardware", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/// <summary> /// Performs the specified SOCKS5 request. /// </summary> /// <param name="request">The SOCKS5 request to issue to the server.</param> /// <returns>The SOCKS5 reply sent by the server.</returns> /// <exception cref="ArgumentNullException">The request parameter is /// null.</exception> /// <exception cref="ObjectDisposedException">The object has been /// disposed.</exception> /// <exception cref="Socks5Exception">The request could not be performed. /// Consult the InnerException property of the Socks5Exception to learn /// the reason.</exception> public SocksReply Request(SocksRequest request) { request.ThrowIfNull("request"); AssertValid(); try { byte[] bytes = request.Serialize(); stream.Write(bytes, 0, bytes.Length); ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp) bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } return SocksReply.Deserialize(b.ToArray()); } catch (Exception e) { throw new Socks5Exception("The request could not be performed.", e); } }
/// <summary> /// Converts the notification information into a packet of data to be sent /// to the Growl receiving application. /// </summary> /// <returns>byte array</returns> private byte[] PrepareData() { int flags = ConvertPriorityToFlag(this.priority); if (this.sticky) flags = flags | 1; ByteBuilder bb = new ByteBuilder(); bb.Append((byte)this.protocolVersion); bb.Append((byte)this.packetType); bb.Append((short)flags); bb.Append(ByteBuilder.GetStringLengthAsShort(this.notificationType.Name)); bb.Append(ByteBuilder.GetStringLengthAsShort(this.title)); bb.Append(ByteBuilder.GetStringLengthAsShort(this.description)); bb.Append(ByteBuilder.GetStringLengthAsShort(this.applicationName)); bb.Append(this.notificationType.Name); bb.Append(this.title); bb.Append(this.description); bb.Append(this.applicationName); // handle the password ByteBuilder pb = new ByteBuilder(); pb.Append(this.password); ByteBuilder bpb = new ByteBuilder(); bpb.Append(bb.GetBytes()); bpb.Append(pb.GetBytes()); byte[] checksum = Cryptography.ComputeHash(bpb.GetBytes(), Cryptography.HashAlgorithmType.MD5); ByteBuilder fb = new ByteBuilder(); fb.Append(bb.GetBytes()); fb.Append(checksum); byte[] data = fb.GetBytes(); return data; }
/// <summary> /// Converts the notification information into a packet of data to be sent /// to the Growl receiving application. /// </summary> /// <returns>byte array</returns> private byte[] PrepareData() { ByteBuilder nb = new ByteBuilder(); ByteBuilder db = new ByteBuilder(); int index = 0; int notificationTypeCount = 0; int notificationTypeEnabledCount = 0; foreach (NotificationType notificationType in this.notificationTypes) { nb.Append(notificationType.Name.Length); nb.Append(notificationType.Name); notificationTypeCount++; if (notificationType.Enabled) { notificationTypeEnabledCount++; db.Append((byte)index); } index++; } ByteBuilder bb = new ByteBuilder(); bb.Append((byte)this.protocolVersion); bb.Append((byte)this.packetType); bb.Append(ByteBuilder.GetStringLengthAsShort(this.applicationName)); bb.Append((byte)notificationTypeCount); bb.Append((byte)notificationTypeEnabledCount); bb.Append(this.applicationName); bb.Append(nb.GetBytes()); bb.Append(db.GetBytes()); // handle the password ByteBuilder pb = new ByteBuilder(); pb.Append(this.password); ByteBuilder bpb = new ByteBuilder(); bpb.Append(bb.GetBytes()); bpb.Append(pb.GetBytes()); byte[] checksum = Cryptography.ComputeHash(bpb.GetBytes(), Cryptography.HashAlgorithmType.MD5); ByteBuilder fb = new ByteBuilder(); fb.Append(bb.GetBytes()); fb.Append(checksum); byte[] data = fb.GetBytes(); return data; }
/// <summary> /// Performs the initial greeting. /// </summary> /// <exception cref="Socks5Exception">The client sent invalid data, or /// requires authentication.</exception> /// <exception cref="IOException">The stream could not be read, or the /// operation timed out.</exception> void PerformGreeting() { ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { byte[] bytes = r.ReadBytes(2); b.Append(bytes); // The number of method-bytes following is contained in the second byte. b.Append(r.ReadBytes(bytes[1])); } ClientGreeting greeting = ClientGreeting.Deserialize(b.ToArray()); // We only accept an authentication method of 'none'. if (!greeting.Methods.Contains(AuthMethod.None)) { Dispose(); throw new Socks5Exception("Client requires authentication."); } // Send back our greeting response. var response = new ServerGreeting(AuthMethod.None).Serialize(); stream.Write(response, 0, response.Length); }
private void buttonFhssLbt_Click(object sender, EventArgs e) { ByteBuilder bb = new ByteBuilder(); UInt16 read_time; UInt16 idle_time; UInt16 sense_time; float rf_level; try { read_time = UInt16.Parse(tbReadTime.Text); idle_time = UInt16.Parse(tbIdleTime.Text); sense_time = UInt16.Parse(tbCwSenseTime.Text); rf_level = float.Parse(tbLbtRfLevel.Text); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } bb.Append(read_time); bb.Append(idle_time); bb.Append(sense_time); bb.Append((UInt16)(rf_level * 10)); if (cbFH.Checked) { bb.Append((byte)1); bb.Append((byte)0); } if (cbLBT.Checked) { bb.Append((byte)0); bb.Append((byte)1); } if (cbFHwithLBT.Checked) { bb.Append((byte)2); bb.Append((byte)1); } if (cbLBTwithFH.Checked) { bb.Append((byte)1); bb.Append((byte)2); } if (cbFH.Checked == false && cbLBT.Checked == false && cbFHwithLBT.Checked == false && cbLBTwithFH.Checked == false) { bb.Append((byte)0); bb.Append((byte)0); bb.Append((byte)0); } //if (cbCW.Checked) bb.Append((byte)1); else { bb.Append((byte)0); } if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_FH_LBT, bb.GetByteArray()))) { } }
/// <summary> /// Waits until the connected client sends a SOCKS5 request. /// </summary> /// <returns>The SOCKS5 request sent by the client.</returns> /// <exception cref="Socks5Exception">The data sent by the client /// is not a valid SOCKS5 request.</exception> SocksRequest WaitForRequest() { ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { byte[] bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp) bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } try { return SocksRequest.Deserialize(b.ToArray()); } catch (Exception e) { throw new Socks5Exception("The request could not be serialized.", e); } }
private static object getRealValue(IDataReader datareader, int ordinal, Type t) { if (t == typeof(Int16)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetInt16(ordinal) : null; if (t == typeof(Int32)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetInt32(ordinal) : null; if (t == typeof(Int64)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetInt32(ordinal) : null; if (t == typeof(Byte[])) { if (datareader.IsDBNull(ordinal)) return null; int bufferSize = 1024; int startIndex = 0; byte[] outbyte = new byte[bufferSize]; ByteBuilder bb = new ByteBuilder(); long retval = datareader.GetBytes(ordinal, startIndex, outbyte, 0, bufferSize); while (retval == bufferSize) { bb.Append(outbyte); startIndex += bufferSize; retval = datareader.GetBytes(ordinal, startIndex, outbyte, 0, bufferSize); } if (retval > 0) bb.Append(outbyte); return bb.GetBytes(); } if (t == typeof(String)) return !datareader.IsDBNull(ordinal) ? datareader.GetString(ordinal) : null; if (t == typeof(DateTime)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetDateTime(ordinal) : null; if (t == typeof(Boolean)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetBoolean(ordinal) : null; if (t == typeof(Double)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetDouble(ordinal) : null; if (t == typeof(Single)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetFloat(ordinal) : null; if (t == typeof(Guid)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetGuid(ordinal) : null; if (t == typeof(Decimal)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetDecimal(ordinal) : null; if (t == typeof(Byte)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetByte(ordinal) : null; return null; }
// Returns the request offset into the builder buffer public UInt32 Build(ByteBuilder builder, HttpClient client, Boolean keepAlive) { if (method == null) { throw new InvalidOperationException("The HttpRequest method must be set"); } // // <METHOD> <resource> HTTP/1.1\r\n // builder.AppendAscii(method); // Todo: Should I verify that method is ascii beforehand? builder.AppendAscii(' '); if (!String.IsNullOrEmpty(resource)) { builder.AppendAscii(resource); // Todo: Should I verify that resource is ascii beforehand? } else if (resourceAppender != null) { resourceAppender(builder); } else { throw new InvalidOperationException("The HttpRequest resource must be set"); } builder.Append(VersionPart); // // Host: <host>[:<port>] // builder.Append(Http.HostHeaderPrefix); if (overrideHostHeader != null) { builder.AppendAscii(overrideHostHeader); } else { builder.AppendAscii(client.IPOrHost); if (client.Port != 80 || forcePortInHostHeader) { builder.AppendAscii(':'); builder.AppendNumber(client.Port, 10); } } builder.Append(Http.Newline); // // Header: Content-Length // // TODO: when do I not need a Content-Length? UInt32 contentLengthOffset = UInt32.MaxValue; { Boolean hasContent; UInt32 contentLength; if (content.contentAsBytes != null) { hasContent = true; contentLength = (UInt32)content.contentAsBytes.Length; } else if (content.contentAsString != null) { hasContent = true; contentLength = content.contentAsStringEncoder.GetEncodeLength(content.contentAsString); } else if (content.contentAppender != null) { hasContent = true; contentLength = UInt32.MaxValue; // Placeholder } else { hasContent = false; contentLength = 0; } if (hasContent) { builder.Append(Http.ContentLengthHeaderPrefix); contentLengthOffset = builder.contentLength; builder.AppendNumber(contentLength); builder.Append(Http.Newline); if (content.contentType != null) { builder.Append(Http.ContentTypeHeaderPrefix); builder.AppendAscii(content.contentType); builder.Append(Http.Newline); } } } // // Header: Connection // if (keepAlive) { builder.Append(Http.ConnectionHeaderPrefix); builder.Append(Http.ConnectionKeepAlive); builder.Append(Http.Newline); } else { builder.Append(Http.ConnectionHeaderPrefix); builder.Append(Http.ConnectionClose); builder.Append(Http.Newline); } // // Extra Headers // if (extraHeaders != null) { builder.Append(extraHeaders); } if (extraHeadersAppender != null) { extraHeadersAppender(builder); } // // End of Headers \r\n\r\n // builder.Append(Http.Newline); // // Content // if (content.contentAsBytes != null) { builder.Append(content.contentAsBytes); } else if (content.contentAsString != null) { builder.Append(content.contentAsStringEncoder, content.contentAsString); } else if (content.contentAppender != null) { // // Get the content // var contentStart = builder.contentLength; content.contentAppender(builder); UInt32 contentLength = builder.contentLength - contentStart; // Patch the request with the new content length UInt32 shift; // Shift everything before Content-Length: value to the right if (contentLength == 0) { builder.bytes[contentLengthOffset + 9] = (Byte)'0'; shift = 9; // Shift everything } else { shift = 9; var temp = contentLength; while (true) { builder.bytes[contentLengthOffset + shift] = (Byte)('0' + (temp % 10)); temp = temp / 10; if (temp == 0) { break; } shift--; } } // Shift the beginning of the request to compensate for a smaller Content-Length if (shift > 0) { var offset = contentLengthOffset - 1; while (true) { builder.bytes[offset + shift] = builder.bytes[offset]; if (offset == 0) { break; } offset--; } } return(shift); } return(0); }
public string ReadValue() { var b = new ByteBuilder(); ValueLength = 0; if (Data[Position] == '\"') { Position++; while (CanRead && Data[Position] != '\r' && Data[Position] != '\n') { if (Data[Position] == '\"' && Data[Position - 1] != '\\') { Position++; break; } b.Append(Data[Position]); Position++; } ValueLength = 1; return(b.ToString()); } else if (Data[Position] == '|' || Data[Position] == '>') { int indent = CurrentLineIndent; SkipLine(); MoveToIndentEnd(); if (CurrentLineIndent < indent) // Technically valid { return(""); } // Remove all comment blocks, makes it easier to handle afterwards indent = CurrentLineIndent; int readLines = 0; bool trim = true; bool blockComment = false; int read = 0; while (CanRead) { char c = (char)Data[Position]; if (c == '\n' || (c == '\r' && Position + 1 < Length && Data[Position + 1] == '\n')) { if (c == '\n') { Position++; } else { Position += 2; } NextLine(); MoveToIndentEnd(indent); if (read > 0) { b.Append((byte)' '); } readLines++; trim = true; read = 0; continue; } if (CurrentLineIndent < indent) // Needs to be checked after to make an exception for empty lines { break; } if (Position + 1 < Length) { if (blockComment) { if (c == '*' && Data[Position + 1] == '/') { blockComment = false; Position++; } Position++; continue; } if (c == '/' && Data[Position + 1] == '/') { SkipLine(); MoveToIndentEnd(indent); readLines++; trim = true; read = 0; continue; } else if (c == '/' && Data[Position + 1] == '*') { blockComment = true; Position++; continue; } } if (trim) { if (c == ' ' || c == '\t') { Position++; continue; } } trim = false; b.Append((byte)c); read++; Position++; } ValueLength = readLines + 1; return(b.ToString().TrimEnd(' ')); } else { while (CanRead && Data[Position] != '\r' && Data[Position] != '\n' && Data[Position] != '#') { b.Append(Data[Position]); Position++; } ValueLength = 1; return(b.ToString().TrimEnd(' ', '\t')); } }
/// <summary> /// Checks to see if a given packets data matches a password /// provided by the receiving client and returns the matching password if found. /// </summary> /// <param name="bytes">The packets data</param> /// <param name="passwordManager">The receiving client's list of passwords</param> /// <param name="passwordRequired">Indicates if the request must supply a valid password</param> /// <param name="password">Returns the matching password if found; null otherwise</param> /// <returns><c>true</c> if the password matches, <c>false</c> otherwise</returns> protected static bool IsPasswordValid(byte[] bytes, PasswordManager passwordManager, bool passwordRequired, out string password) { password = null; byte[] packetWithoutPassword = new byte[bytes.Length - 16]; Array.Copy(bytes, 0, packetWithoutPassword, 0, packetWithoutPassword.Length); byte[] thatChecksum = new byte[16]; Array.Copy(bytes, bytes.Length - 16, thatChecksum, 0, 16); string thatChecksumString = Encoding.UTF8.GetString(thatChecksum); ByteBuilder bpb = new ByteBuilder(); bpb.Append(packetWithoutPassword); Queue<string> validPasswords = new Queue<string>(); foreach (KeyValuePair<string, Password> item in passwordManager.Passwords) { validPasswords.Enqueue(item.Key); } // if the request does not require a password, then // we can also try no (blank) password if (!passwordRequired) validPasswords.Enqueue(String.Empty); while(validPasswords.Count > 0) { string p = validPasswords.Dequeue(); ByteBuilder pb = new ByteBuilder(); pb.Append(bpb.GetBytes()); pb.Append(p); byte[] thisChecksum = Cryptography.ComputeHash(pb.GetBytes(), Cryptography.HashAlgorithmType.MD5); string thisChecksumString = Encoding.UTF8.GetString(thisChecksum); if (thisChecksumString == thatChecksumString) { password = p; return true; } } return false; }