SshdConfig.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. using System.Globalization;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using Renci.SshNet.TestTools.OpenSSH.Formatters;
  5. namespace Renci.SshNet.TestTools.OpenSSH
  6. {
  7. public class SshdConfig
  8. {
  9. private static readonly Regex MatchRegex = new Regex($@"\s*Match\s+(User\s+(?<users>[\S]+))?\s*(Address\s+(?<addresses>[\S]+))?\s*", RegexOptions.Compiled);
  10. private readonly SubsystemFormatter _subsystemFormatter;
  11. private readonly Int32Formatter _int32Formatter;
  12. private readonly BooleanFormatter _booleanFormatter;
  13. private readonly MatchFormatter _matchFormatter;
  14. private SshdConfig()
  15. {
  16. AcceptedEnvironmentVariables = new List<string>();
  17. Ciphers = new List<Cipher>();
  18. HostKeyFiles = new List<string>();
  19. HostKeyAlgorithms = new List<HostKeyAlgorithm>();
  20. KeyExchangeAlgorithms = new List<KeyExchangeAlgorithm>();
  21. PublicKeyAcceptedAlgorithms = new List<PublicKeyAlgorithm>();
  22. MessageAuthenticationCodeAlgorithms = new List<MessageAuthenticationCodeAlgorithm>();
  23. Subsystems = new List<Subsystem>();
  24. Matches = new List<Match>();
  25. LogLevel = LogLevel.Info;
  26. Port = 22;
  27. Protocol = "2,1";
  28. _booleanFormatter = new BooleanFormatter();
  29. _int32Formatter = new Int32Formatter();
  30. _matchFormatter = new MatchFormatter();
  31. _subsystemFormatter = new SubsystemFormatter();
  32. }
  33. /// <summary>
  34. /// Gets or sets the port number that sshd listens on.
  35. /// </summary>
  36. /// <value>
  37. /// The port number that sshd listens on. The default is 22.
  38. /// </value>
  39. public int Port { get; set; }
  40. /// <summary>
  41. /// Gets or sets the list of private host key files used by sshd.
  42. /// </summary>
  43. /// <value>
  44. /// A list of private host key files used by sshd.
  45. /// </value>
  46. public List<string> HostKeyFiles { get; set; }
  47. /// <summary>
  48. /// Gets or sets a value specifying whether challenge-response authentication is allowed.
  49. /// </summary>
  50. /// <value>
  51. /// A value specifying whether challenge-response authentication is allowed, or <see langword="null"/>
  52. /// if this option is not configured.
  53. /// </value>
  54. public bool? ChallengeResponseAuthentication { get; set; }
  55. /// <summary>
  56. /// Gets or sets a value indicating whether to allow keyboard-interactive authentication.
  57. /// </summary>
  58. /// <value>
  59. /// <see langword="true"/> to allow and <see langword="false"/> to disallow keyboard-interactive
  60. /// authentication, or <see langword="null"/> if this option is not configured.
  61. /// </value>
  62. public bool? KeyboardInteractiveAuthentication { get; set; }
  63. /// <summary>
  64. /// Gets or sets the verbosity when logging messages from sshd.
  65. /// </summary>
  66. /// <value>
  67. /// The verbosity when logging messages from sshd. The default is <see cref="LogLevel.Info"/>.
  68. /// </value>
  69. public LogLevel LogLevel { get; set; }
  70. /// <summary>
  71. /// Gets a sets a value indicating whether the Pluggable Authentication Module interface is enabled.
  72. /// </summary>
  73. /// <value>
  74. /// A value indicating whether the Pluggable Authentication Module interface is enabled.
  75. /// </value>
  76. public bool? UsePAM { get; set; }
  77. public List<Subsystem> Subsystems { get; }
  78. /// <summary>
  79. /// Gets a list of conditional blocks.
  80. /// </summary>
  81. public List<Match> Matches { get; }
  82. public bool X11Forwarding { get; private set; }
  83. public List<string> AcceptedEnvironmentVariables { get; private set; }
  84. public List<Cipher> Ciphers { get; private set; }
  85. /// <summary>
  86. /// Gets the host key signature algorithms that the server offers.
  87. /// </summary>
  88. public List<HostKeyAlgorithm> HostKeyAlgorithms { get; private set; }
  89. /// <summary>
  90. /// Gets the available KEX (Key Exchange) algorithms.
  91. /// </summary>
  92. public List<KeyExchangeAlgorithm> KeyExchangeAlgorithms { get; private set; }
  93. /// <summary>
  94. /// Gets the signature algorithms that will be accepted for public key authentication.
  95. /// </summary>
  96. public List<PublicKeyAlgorithm> PublicKeyAcceptedAlgorithms { get; private set; }
  97. /// <summary>
  98. /// Gets the available MAC (message authentication code) algorithms.
  99. /// </summary>
  100. public List<MessageAuthenticationCodeAlgorithm> MessageAuthenticationCodeAlgorithms { get; private set; }
  101. /// <summary>
  102. /// Gets a value indicating whether <c>sshd</c> should print <c>/etc/motd</c> when a user logs in interactively.
  103. /// </summary>
  104. /// <value>
  105. /// <see langword="true"/> if <c>sshd</c> should print <c>/etc/motd</c> when a user logs in interactively
  106. /// and <see langword="false"/> if it should not; <see langword="null"/> if this option is not configured.
  107. /// </value>
  108. public bool? PrintMotd { get; set; }
  109. /// <summary>
  110. /// Gets or sets the protocol versions sshd supported.
  111. /// </summary>
  112. /// <value>
  113. /// The protocol versions sshd supported. The default is <c>2,1</c>.
  114. /// </value>
  115. public string Protocol { get; set; }
  116. /// <summary>
  117. /// Gets or sets a value indicating whether TCP forwarding is allowed.
  118. /// </summary>
  119. /// <value>
  120. /// <see langword="true"/> to allow and <see langword="false"/> to disallow TCP forwarding,
  121. /// or <see langword="null"/> if this option is not configured.
  122. /// </value>
  123. public bool? AllowTcpForwarding { get; set; }
  124. public void SaveTo(TextWriter writer)
  125. {
  126. writer.WriteLine("Protocol " + Protocol);
  127. writer.WriteLine("Port " + _int32Formatter.Format(Port));
  128. if (HostKeyFiles.Count > 0)
  129. {
  130. writer.WriteLine("HostKey " + string.Join(",", HostKeyFiles.ToArray()));
  131. }
  132. if (ChallengeResponseAuthentication is not null)
  133. {
  134. writer.WriteLine("ChallengeResponseAuthentication " + _booleanFormatter.Format(ChallengeResponseAuthentication.Value));
  135. }
  136. if (KeyboardInteractiveAuthentication is not null)
  137. {
  138. writer.WriteLine("KbdInteractiveAuthentication " + _booleanFormatter.Format(KeyboardInteractiveAuthentication.Value));
  139. }
  140. if (AllowTcpForwarding is not null)
  141. {
  142. writer.WriteLine("AllowTcpForwarding " + _booleanFormatter.Format(AllowTcpForwarding.Value));
  143. }
  144. if (PrintMotd is not null)
  145. {
  146. writer.WriteLine("PrintMotd " + _booleanFormatter.Format(PrintMotd.Value));
  147. }
  148. writer.WriteLine("LogLevel " + new LogLevelFormatter().Format(LogLevel));
  149. foreach (var subsystem in Subsystems)
  150. {
  151. writer.WriteLine("Subsystem " + _subsystemFormatter.Format(subsystem));
  152. }
  153. if (UsePAM is not null)
  154. {
  155. writer.WriteLine("UsePAM " + _booleanFormatter.Format(UsePAM.Value));
  156. }
  157. writer.WriteLine("X11Forwarding " + _booleanFormatter.Format(X11Forwarding));
  158. foreach (var acceptedEnvVar in AcceptedEnvironmentVariables)
  159. {
  160. writer.WriteLine("AcceptEnv " + acceptedEnvVar);
  161. }
  162. if (Ciphers.Count > 0)
  163. {
  164. writer.WriteLine("Ciphers " + string.Join(",", Ciphers.Select(c => c.Name).ToArray()));
  165. }
  166. if (HostKeyAlgorithms.Count > 0)
  167. {
  168. writer.WriteLine("HostKeyAlgorithms " + string.Join(",", HostKeyAlgorithms.Select(c => c.Name).ToArray()));
  169. }
  170. if (KeyExchangeAlgorithms.Count > 0)
  171. {
  172. writer.WriteLine("KexAlgorithms " + string.Join(",", KeyExchangeAlgorithms.Select(c => c.Name).ToArray()));
  173. }
  174. if (MessageAuthenticationCodeAlgorithms.Count > 0)
  175. {
  176. writer.WriteLine("MACs " + string.Join(",", MessageAuthenticationCodeAlgorithms.Select(c => c.Name).ToArray()));
  177. }
  178. if (PublicKeyAcceptedAlgorithms.Count > 0)
  179. {
  180. writer.WriteLine("PubkeyAcceptedAlgorithms " + string.Join(",", PublicKeyAcceptedAlgorithms.Select(c => c.Name).ToArray()));
  181. }
  182. foreach (var match in Matches)
  183. {
  184. _matchFormatter.Format(match, writer);
  185. }
  186. }
  187. public static SshdConfig LoadFrom(Stream stream, Encoding encoding)
  188. {
  189. using (var sr = new StreamReader(stream, encoding))
  190. {
  191. var sshdConfig = new SshdConfig();
  192. Match? currentMatchConfiguration = null;
  193. string? line;
  194. while ((line = sr.ReadLine()) != null)
  195. {
  196. // Skip empty lines
  197. if (line.Length == 0)
  198. {
  199. continue;
  200. }
  201. // Skip comments
  202. if (line[0] == '#')
  203. {
  204. continue;
  205. }
  206. var match = MatchRegex.Match(line);
  207. if (match.Success)
  208. {
  209. var usersGroup = match.Groups["users"];
  210. var addressesGroup = match.Groups["addresses"];
  211. var users = usersGroup.Success ? usersGroup.Value.Split(',') : Array.Empty<string>();
  212. var addresses = addressesGroup.Success ? addressesGroup.Value.Split(',') : Array.Empty<string>();
  213. currentMatchConfiguration = new Match(users, addresses);
  214. sshdConfig.Matches.Add(currentMatchConfiguration);
  215. continue;
  216. }
  217. if (currentMatchConfiguration != null)
  218. {
  219. ProcessMatchOption(currentMatchConfiguration, line);
  220. }
  221. else
  222. {
  223. ProcessGlobalOption(sshdConfig, line);
  224. }
  225. }
  226. if (sshdConfig.Ciphers == null)
  227. {
  228. // Obtain supported ciphers using ssh -Q cipher
  229. }
  230. if (sshdConfig.KeyExchangeAlgorithms == null)
  231. {
  232. // Obtain supports key exchange algorithms using ssh -Q kex
  233. }
  234. if (sshdConfig.HostKeyAlgorithms == null)
  235. {
  236. // Obtain supports host key algorithms using ssh -Q key
  237. }
  238. if (sshdConfig.MessageAuthenticationCodeAlgorithms == null)
  239. {
  240. // Obtain supported MACs using ssh -Q mac
  241. }
  242. return sshdConfig;
  243. }
  244. }
  245. private static void ProcessGlobalOption(SshdConfig sshdConfig, string line)
  246. {
  247. var matchOptionRegex = new Regex(@"^\s*(?<name>[\S]+)\s+(?<value>.+?){1}\s*$");
  248. var optionsMatch = matchOptionRegex.Match(line);
  249. if (!optionsMatch.Success)
  250. {
  251. return;
  252. }
  253. var nameGroup = optionsMatch.Groups["name"];
  254. var valueGroup = optionsMatch.Groups["value"];
  255. var name = nameGroup.Value;
  256. var value = valueGroup.Value;
  257. switch (name)
  258. {
  259. case "Port":
  260. sshdConfig.Port = ToInt(value);
  261. break;
  262. case "HostKey":
  263. sshdConfig.HostKeyFiles = ParseCommaSeparatedValue(value);
  264. break;
  265. case "ChallengeResponseAuthentication":
  266. sshdConfig.ChallengeResponseAuthentication = ToBool(value);
  267. break;
  268. case "KbdInteractiveAuthentication":
  269. sshdConfig.KeyboardInteractiveAuthentication = ToBool(value);
  270. break;
  271. case "LogLevel":
  272. sshdConfig.LogLevel = (LogLevel) Enum.Parse(typeof(LogLevel), value, true);
  273. break;
  274. case "Subsystem":
  275. sshdConfig.Subsystems.Add(Subsystem.FromConfig(value));
  276. break;
  277. case "UsePAM":
  278. sshdConfig.UsePAM = ToBool(value);
  279. break;
  280. case "X11Forwarding":
  281. sshdConfig.X11Forwarding = ToBool(value);
  282. break;
  283. case "Ciphers":
  284. sshdConfig.Ciphers = ParseCiphers(value);
  285. break;
  286. case "KexAlgorithms":
  287. sshdConfig.KeyExchangeAlgorithms = ParseKeyExchangeAlgorithms(value);
  288. break;
  289. case "PubkeyAcceptedAlgorithms":
  290. sshdConfig.PublicKeyAcceptedAlgorithms = ParsePublicKeyAcceptedAlgorithms(value);
  291. break;
  292. case "HostKeyAlgorithms":
  293. sshdConfig.HostKeyAlgorithms = ParseHostKeyAlgorithms(value);
  294. break;
  295. case "MACs":
  296. sshdConfig.MessageAuthenticationCodeAlgorithms = ParseMacs(value);
  297. break;
  298. case "PrintMotd":
  299. sshdConfig.PrintMotd = ToBool(value);
  300. break;
  301. case "AcceptEnv":
  302. ParseAcceptedEnvironmentVariable(sshdConfig, value);
  303. break;
  304. case "Protocol":
  305. sshdConfig.Protocol = value;
  306. break;
  307. case "AllowTcpForwarding":
  308. sshdConfig.AllowTcpForwarding = ToBool(value);
  309. break;
  310. case "KeyRegenerationInterval":
  311. case "HostbasedAuthentication":
  312. case "ServerKeyBits":
  313. case "SyslogFacility":
  314. case "LoginGraceTime":
  315. case "PermitRootLogin":
  316. case "StrictModes":
  317. case "RSAAuthentication":
  318. case "PubkeyAuthentication":
  319. case "IgnoreRhosts":
  320. case "RhostsRSAAuthentication":
  321. case "PermitEmptyPasswords":
  322. case "X11DisplayOffset":
  323. case "PrintLastLog":
  324. case "TCPKeepAlive":
  325. case "AuthorizedKeysFile":
  326. case "PasswordAuthentication":
  327. case "GatewayPorts":
  328. break;
  329. default:
  330. throw new Exception($"Global option '{name}' is not implemented.");
  331. }
  332. }
  333. private static void ParseAcceptedEnvironmentVariable(SshdConfig sshdConfig, string value)
  334. {
  335. var acceptedEnvironmentVariables = value.Split(' ');
  336. foreach (var acceptedEnvironmentVariable in acceptedEnvironmentVariables)
  337. {
  338. sshdConfig.AcceptedEnvironmentVariables.Add(acceptedEnvironmentVariable);
  339. }
  340. }
  341. private static List<Cipher> ParseCiphers(string value)
  342. {
  343. var cipherNames = value.Split(',');
  344. var ciphers = new List<Cipher>(cipherNames.Length);
  345. foreach (var cipherName in cipherNames)
  346. {
  347. ciphers.Add(new Cipher(cipherName.Trim()));
  348. }
  349. return ciphers;
  350. }
  351. private static List<KeyExchangeAlgorithm> ParseKeyExchangeAlgorithms(string value)
  352. {
  353. var kexNames = value.Split(',');
  354. var keyExchangeAlgorithms = new List<KeyExchangeAlgorithm>(kexNames.Length);
  355. foreach (var kexName in kexNames)
  356. {
  357. keyExchangeAlgorithms.Add(new KeyExchangeAlgorithm(kexName.Trim()));
  358. }
  359. return keyExchangeAlgorithms;
  360. }
  361. public static List<PublicKeyAlgorithm> ParsePublicKeyAcceptedAlgorithms(string value)
  362. {
  363. var publicKeyAlgorithmNames = value.Split(',');
  364. var publicKeyAlgorithms = new List<PublicKeyAlgorithm>(publicKeyAlgorithmNames.Length);
  365. foreach (var publicKeyAlgorithmName in publicKeyAlgorithmNames)
  366. {
  367. publicKeyAlgorithms.Add(new PublicKeyAlgorithm(publicKeyAlgorithmName.Trim()));
  368. }
  369. return publicKeyAlgorithms;
  370. }
  371. private static List<HostKeyAlgorithm> ParseHostKeyAlgorithms(string value)
  372. {
  373. var algorithmNames = value.Split(',');
  374. var hostKeyAlgorithms = new List<HostKeyAlgorithm>(algorithmNames.Length);
  375. foreach (var algorithmName in algorithmNames)
  376. {
  377. hostKeyAlgorithms.Add(new HostKeyAlgorithm(algorithmName.Trim()));
  378. }
  379. return hostKeyAlgorithms;
  380. }
  381. private static List<MessageAuthenticationCodeAlgorithm> ParseMacs(string value)
  382. {
  383. var macNames = value.Split(',');
  384. var macAlgorithms = new List<MessageAuthenticationCodeAlgorithm>(macNames.Length);
  385. foreach (var algorithmName in macNames)
  386. {
  387. macAlgorithms.Add(new MessageAuthenticationCodeAlgorithm(algorithmName.Trim()));
  388. }
  389. return macAlgorithms;
  390. }
  391. private static void ProcessMatchOption(Match matchConfiguration, string line)
  392. {
  393. var matchOptionRegex = new Regex(@"^\s+(?<name>[\S]+)\s+(?<value>.+?){1}\s*$");
  394. var optionsMatch = matchOptionRegex.Match(line);
  395. if (!optionsMatch.Success)
  396. {
  397. return;
  398. }
  399. var nameGroup = optionsMatch.Groups["name"];
  400. var valueGroup = optionsMatch.Groups["value"];
  401. var name = nameGroup.Value;
  402. var value = valueGroup.Value;
  403. switch (name)
  404. {
  405. case "AuthenticationMethods":
  406. matchConfiguration.AuthenticationMethods = value;
  407. break;
  408. default:
  409. throw new Exception($"Match option '{name}' is not implemented.");
  410. }
  411. }
  412. private static List<string> ParseCommaSeparatedValue(string value)
  413. {
  414. var values = value.Split(',');
  415. return new List<string>(values);
  416. }
  417. private static bool ToBool(string value)
  418. {
  419. switch (value)
  420. {
  421. case "yes":
  422. return true;
  423. case "no":
  424. return false;
  425. default:
  426. throw new Exception($"Value '{value}' cannot be mapped to a boolean.");
  427. }
  428. }
  429. private static int ToInt(string value)
  430. {
  431. return int.Parse(value, NumberFormatInfo.InvariantInfo);
  432. }
  433. }
  434. }