DhcpMessage.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2020 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.Dhcp.Options;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Net;
  20. using System.Net.Sockets;
  21. using TechnitiumLibrary.IO;
  22. namespace DnsServerCore.Dhcp
  23. {
  24. enum DhcpMessageOpCode : byte
  25. {
  26. BootRequest = 1,
  27. BootReply = 2
  28. }
  29. enum DhcpMessageHardwareAddressType : byte
  30. {
  31. Ethernet = 1
  32. }
  33. enum DhcpMessageFlags : ushort
  34. {
  35. None = 0,
  36. Broadcast = 0x8000
  37. }
  38. class DhcpMessage
  39. {
  40. #region variables
  41. const uint MAGIC_COOKIE = 0x63538263; //in reverse format
  42. readonly DhcpMessageOpCode _op;
  43. readonly DhcpMessageHardwareAddressType _htype;
  44. readonly byte _hlen;
  45. readonly byte _hops;
  46. readonly byte[] _xid;
  47. readonly byte[] _secs;
  48. readonly DhcpMessageFlags _flags;
  49. readonly IPAddress _ciaddr;
  50. readonly IPAddress _yiaddr;
  51. readonly IPAddress _siaddr;
  52. readonly IPAddress _giaddr;
  53. readonly byte[] _chaddr;
  54. readonly byte[] _sname;
  55. readonly byte[] _file;
  56. readonly IReadOnlyCollection<DhcpOption> _options;
  57. readonly byte[] _clientHardwareAddress;
  58. OptionOverloadOption _optionOverload;
  59. DhcpMessageTypeOption _dhcpMessageType;
  60. ClientIdentifierOption _clientIdentifier;
  61. HostNameOption _hostName;
  62. ClientFullyQualifiedDomainNameOption _clientFullyQualifiedDomainName;
  63. ParameterRequestListOption _parameterRequestList;
  64. MaximumDhcpMessageSizeOption _maximumDhcpMessageSize;
  65. ServerIdentifierOption _serverIdentifier;
  66. RequestedIpAddressOption _requestedIpAddress;
  67. #endregion
  68. #region constructor
  69. public DhcpMessage(DhcpMessageOpCode op, DhcpMessageHardwareAddressType hardwareAddressType, byte[] xid, byte[] secs, DhcpMessageFlags flags, IPAddress ciaddr, IPAddress yiaddr, IPAddress siaddr, IPAddress giaddr, byte[] clientHardwareAddress, IReadOnlyCollection<DhcpOption> options)
  70. {
  71. if (ciaddr.AddressFamily != AddressFamily.InterNetwork)
  72. throw new ArgumentException("Address family not supported.", nameof(ciaddr));
  73. if (yiaddr.AddressFamily != AddressFamily.InterNetwork)
  74. throw new ArgumentException("Address family not supported.", nameof(yiaddr));
  75. if (siaddr.AddressFamily != AddressFamily.InterNetwork)
  76. throw new ArgumentException("Address family not supported.", nameof(siaddr));
  77. if (giaddr.AddressFamily != AddressFamily.InterNetwork)
  78. throw new ArgumentException("Address family not supported.", nameof(giaddr));
  79. if (clientHardwareAddress == null)
  80. throw new ArgumentNullException(nameof(clientHardwareAddress));
  81. if (clientHardwareAddress.Length > 16)
  82. throw new ArgumentException("Client hardware address cannot exceed 16 bytes.", "chaddr");
  83. if (xid.Length != 4)
  84. throw new ArgumentException("Transaction ID must be 4 bytes.", nameof(xid));
  85. if (secs.Length != 2)
  86. throw new ArgumentException("Seconds elapsed must be 2 bytes.", nameof(secs));
  87. _op = op;
  88. _htype = hardwareAddressType;
  89. _hlen = Convert.ToByte(clientHardwareAddress.Length);
  90. _hops = 0;
  91. _xid = xid;
  92. _secs = secs;
  93. _flags = flags;
  94. _ciaddr = ciaddr;
  95. _yiaddr = yiaddr;
  96. _siaddr = siaddr;
  97. _giaddr = giaddr;
  98. _clientHardwareAddress = clientHardwareAddress;
  99. _chaddr = new byte[16];
  100. Buffer.BlockCopy(_clientHardwareAddress, 0, _chaddr, 0, _clientHardwareAddress.Length);
  101. _sname = new byte[64];
  102. _file = new byte[128];
  103. _options = options;
  104. }
  105. public DhcpMessage(DhcpMessage request, IPAddress yiaddr, IPAddress siaddr, IReadOnlyCollection<DhcpOption> options)
  106. : this(DhcpMessageOpCode.BootReply,request.HardwareAddressType, request.TransactionId, request.SecondsElapsed, request.Flags, request.ClientIpAddress, yiaddr, siaddr, request.RelayAgentIpAddress, request.ClientHardwareAddress, options)
  107. { }
  108. public DhcpMessage(Stream s)
  109. {
  110. byte[] buffer = new byte[4];
  111. s.ReadBytes(buffer, 0, 4);
  112. _op = (DhcpMessageOpCode)buffer[0];
  113. _htype = (DhcpMessageHardwareAddressType)buffer[1];
  114. _hlen = buffer[2];
  115. _hops = buffer[3];
  116. _xid = s.ReadBytes(4);
  117. s.ReadBytes(buffer, 0, 4);
  118. _secs = new byte[2];
  119. Buffer.BlockCopy(buffer, 0, _secs, 0, 2);
  120. Array.Reverse(buffer);
  121. _flags = (DhcpMessageFlags)BitConverter.ToUInt16(buffer, 0);
  122. s.ReadBytes(buffer, 0, 4);
  123. _ciaddr = new IPAddress(buffer);
  124. s.ReadBytes(buffer, 0, 4);
  125. _yiaddr = new IPAddress(buffer);
  126. s.ReadBytes(buffer, 0, 4);
  127. _siaddr = new IPAddress(buffer);
  128. s.ReadBytes(buffer, 0, 4);
  129. _giaddr = new IPAddress(buffer);
  130. _chaddr = s.ReadBytes(16);
  131. _clientHardwareAddress = new byte[_hlen];
  132. Buffer.BlockCopy(_chaddr, 0, _clientHardwareAddress, 0, _hlen);
  133. _sname = s.ReadBytes(64);
  134. _file = s.ReadBytes(128);
  135. //read options
  136. List<DhcpOption> options = new List<DhcpOption>();
  137. _options = options;
  138. s.ReadBytes(buffer, 0, 4);
  139. uint magicCookie = BitConverter.ToUInt32(buffer, 0);
  140. if (magicCookie == MAGIC_COOKIE)
  141. {
  142. ParseOptions(s, options);
  143. if (_optionOverload != null)
  144. {
  145. if (_optionOverload.Value.HasFlag(OptionOverloadValue.FileFieldUsed))
  146. {
  147. using (MemoryStream mS = new MemoryStream(_file))
  148. {
  149. ParseOptions(mS, options);
  150. }
  151. }
  152. if (_optionOverload.Value.HasFlag(OptionOverloadValue.SnameFieldUsed))
  153. {
  154. using (MemoryStream mS = new MemoryStream(_sname))
  155. {
  156. ParseOptions(mS, options);
  157. }
  158. }
  159. }
  160. //parse all option values
  161. foreach (DhcpOption option in options)
  162. option.ParseOptionValue();
  163. }
  164. if (_clientIdentifier == null)
  165. _clientIdentifier = new ClientIdentifierOption((byte)_htype, _clientHardwareAddress);
  166. if (_maximumDhcpMessageSize != null)
  167. _maximumDhcpMessageSize = new MaximumDhcpMessageSizeOption(576);
  168. }
  169. #endregion
  170. #region private
  171. private void ParseOptions(Stream s, List<DhcpOption> options)
  172. {
  173. while (true)
  174. {
  175. DhcpOption option = DhcpOption.Parse(s);
  176. if (option.Code == DhcpOptionCode.End)
  177. break;
  178. if (option.Code == DhcpOptionCode.Pad)
  179. continue;
  180. bool optionExists = false;
  181. foreach (DhcpOption existingOption in options)
  182. {
  183. if (existingOption.Code == option.Code)
  184. {
  185. //option already exists so append current option value into existing option
  186. existingOption.AppendOptionValue(option);
  187. optionExists = true;
  188. break;
  189. }
  190. }
  191. if (optionExists)
  192. continue;
  193. //add option to list
  194. options.Add(option);
  195. switch (option.Code)
  196. {
  197. case DhcpOptionCode.DhcpMessageType:
  198. _dhcpMessageType = option as DhcpMessageTypeOption;
  199. break;
  200. case DhcpOptionCode.ClientIdentifier:
  201. _clientIdentifier = option as ClientIdentifierOption;
  202. break;
  203. case DhcpOptionCode.HostName:
  204. _hostName = option as HostNameOption;
  205. break;
  206. case DhcpOptionCode.ClientFullyQualifiedDomainName:
  207. _clientFullyQualifiedDomainName = option as ClientFullyQualifiedDomainNameOption;
  208. break;
  209. case DhcpOptionCode.ParameterRequestList:
  210. _parameterRequestList = option as ParameterRequestListOption;
  211. break;
  212. case DhcpOptionCode.MaximumDhcpMessageSize:
  213. _maximumDhcpMessageSize = option as MaximumDhcpMessageSizeOption;
  214. break;
  215. case DhcpOptionCode.ServerIdentifier:
  216. _serverIdentifier = option as ServerIdentifierOption;
  217. break;
  218. case DhcpOptionCode.RequestedIpAddress:
  219. _requestedIpAddress = option as RequestedIpAddressOption;
  220. break;
  221. case DhcpOptionCode.OptionOverload:
  222. _optionOverload = option as OptionOverloadOption;
  223. break;
  224. }
  225. }
  226. }
  227. #endregion
  228. #region public
  229. public void WriteTo(Stream s)
  230. {
  231. s.WriteByte((byte)_op);
  232. s.WriteByte((byte)_htype);
  233. s.WriteByte(_hlen);
  234. s.WriteByte(_hops);
  235. s.Write(_xid);
  236. s.Write(_secs);
  237. byte[] buffer = BitConverter.GetBytes((ushort)_flags);
  238. Array.Reverse(buffer);
  239. s.Write(buffer);
  240. s.Write(_ciaddr.GetAddressBytes());
  241. s.Write(_yiaddr.GetAddressBytes());
  242. s.Write(_siaddr.GetAddressBytes());
  243. s.Write(_giaddr.GetAddressBytes());
  244. s.Write(_chaddr);
  245. s.Write(_sname);
  246. s.Write(_file);
  247. //write options
  248. s.Write(BitConverter.GetBytes(MAGIC_COOKIE));
  249. foreach (DhcpOption option in _options)
  250. option.WriteTo(s);
  251. }
  252. public string GetClientFullIdentifier()
  253. {
  254. string hardwareAddress = BitConverter.ToString(_clientHardwareAddress);
  255. if (_clientFullyQualifiedDomainName != null)
  256. return _clientFullyQualifiedDomainName.DomainName + " [" + hardwareAddress + "]";
  257. if (_hostName != null)
  258. return _hostName.HostName + " [" + hardwareAddress + "]";
  259. return "[" + hardwareAddress + "]";
  260. }
  261. #endregion
  262. #region properties
  263. public DhcpMessageOpCode OpCode
  264. { get { return _op; } }
  265. public DhcpMessageHardwareAddressType HardwareAddressType
  266. { get { return _htype; } }
  267. public byte HardwareAddressLength
  268. { get { return _hlen; } }
  269. public byte Hops
  270. { get { return _hops; } }
  271. public byte[] TransactionId
  272. { get { return _xid; } }
  273. public byte[] SecondsElapsed
  274. { get { return _secs; } }
  275. public DhcpMessageFlags Flags
  276. { get { return _flags; } }
  277. public IPAddress ClientIpAddress
  278. { get { return _ciaddr; } }
  279. public IPAddress YourClientIpAddress
  280. { get { return _yiaddr; } }
  281. public IPAddress NextServerIpAddress
  282. { get { return _siaddr; } }
  283. public IPAddress RelayAgentIpAddress
  284. { get { return _giaddr; } }
  285. public byte[] ClientHardwareAddress
  286. { get { return _clientHardwareAddress; } }
  287. public byte[] ServerHostName
  288. { get { return _sname; } }
  289. public byte[] BootFileName
  290. { get { return _file; } }
  291. public IReadOnlyCollection<DhcpOption> Options
  292. { get { return _options; } }
  293. public DhcpMessageTypeOption DhcpMessageType
  294. { get { return _dhcpMessageType; } }
  295. public ClientIdentifierOption ClientIdentifier
  296. { get { return _clientIdentifier; } }
  297. public HostNameOption HostName
  298. { get { return _hostName; } }
  299. public ClientFullyQualifiedDomainNameOption ClientFullyQualifiedDomainName
  300. { get { return _clientFullyQualifiedDomainName; } }
  301. public ParameterRequestListOption ParameterRequestList
  302. { get { return _parameterRequestList; } }
  303. public MaximumDhcpMessageSizeOption MaximumDhcpMessageSize
  304. { get { return _maximumDhcpMessageSize; } }
  305. public ServerIdentifierOption ServerIdentifier
  306. { get { return _serverIdentifier; } }
  307. public RequestedIpAddressOption RequestedIpAddress
  308. { get { return _requestedIpAddress; } }
  309. #endregion
  310. }
  311. }