SshdConfig.cs 20 KB

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