SshdConfig.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 TCP forwarding is allowed.
  119. /// </summary>
  120. /// <value>
  121. /// <see langword="true"/> to allow and <see langword="false"/> to disallow TCP forwarding,
  122. /// or <see langword="null"/> if this option is not configured.
  123. /// </value>
  124. public bool? AllowTcpForwarding { get; set; }
  125. public static SshdConfig LoadFrom(Stream stream, Encoding encoding)
  126. {
  127. using (var sr = new StreamReader(stream, encoding))
  128. {
  129. var sshdConfig = new SshdConfig();
  130. Match? currentMatchConfiguration = null;
  131. string? line;
  132. while ((line = sr.ReadLine()) != null)
  133. {
  134. // Skip empty lines
  135. if (line.Length == 0)
  136. {
  137. continue;
  138. }
  139. // Skip comments
  140. if (line[0] == '#')
  141. {
  142. continue;
  143. }
  144. var match = MatchRegex.Match(line);
  145. if (match.Success)
  146. {
  147. var usersGroup = match.Groups["users"];
  148. var addressesGroup = match.Groups["addresses"];
  149. var users = usersGroup.Success ? usersGroup.Value.Split(',') : Array.Empty<string>();
  150. var addresses = addressesGroup.Success ? addressesGroup.Value.Split(',') : Array.Empty<string>();
  151. currentMatchConfiguration = new Match(users, addresses);
  152. sshdConfig.Matches.Add(currentMatchConfiguration);
  153. continue;
  154. }
  155. if (currentMatchConfiguration != null)
  156. {
  157. ProcessMatchOption(currentMatchConfiguration, line);
  158. }
  159. else
  160. {
  161. ProcessGlobalOption(sshdConfig, line);
  162. }
  163. }
  164. if (sshdConfig.Ciphers == null)
  165. {
  166. // Obtain supported ciphers using ssh -Q cipher
  167. }
  168. if (sshdConfig.KeyExchangeAlgorithms == null)
  169. {
  170. // Obtain supports key exchange algorithms using ssh -Q kex
  171. }
  172. if (sshdConfig.HostKeyAlgorithms == null)
  173. {
  174. // Obtain supports host key algorithms using ssh -Q key
  175. }
  176. if (sshdConfig.MessageAuthenticationCodeAlgorithms == null)
  177. {
  178. // Obtain supported MACs using ssh -Q mac
  179. }
  180. return sshdConfig;
  181. }
  182. }
  183. public void SaveTo(TextWriter writer)
  184. {
  185. if (writer is null)
  186. {
  187. throw new ArgumentNullException(nameof(writer));
  188. }
  189. writer.WriteLine("Protocol " + Protocol);
  190. writer.WriteLine("Port " + _int32Formatter.Format(Port));
  191. if (HostKeyFiles.Count > 0)
  192. {
  193. writer.WriteLine("HostKey " + string.Join(",", HostKeyFiles.ToArray()));
  194. }
  195. if (ChallengeResponseAuthentication is not null)
  196. {
  197. writer.WriteLine("ChallengeResponseAuthentication " + _booleanFormatter.Format(ChallengeResponseAuthentication.Value));
  198. }
  199. if (KeyboardInteractiveAuthentication is not null)
  200. {
  201. writer.WriteLine("KbdInteractiveAuthentication " + _booleanFormatter.Format(KeyboardInteractiveAuthentication.Value));
  202. }
  203. if (AllowTcpForwarding is not null)
  204. {
  205. writer.WriteLine("AllowTcpForwarding " + _booleanFormatter.Format(AllowTcpForwarding.Value));
  206. }
  207. if (PrintMotd is not null)
  208. {
  209. writer.WriteLine("PrintMotd " + _booleanFormatter.Format(PrintMotd.Value));
  210. }
  211. writer.WriteLine("LogLevel " + new LogLevelFormatter().Format(LogLevel));
  212. foreach (var subsystem in Subsystems)
  213. {
  214. writer.WriteLine("Subsystem " + _subsystemFormatter.Format(subsystem));
  215. }
  216. if (UsePAM is not null)
  217. {
  218. writer.WriteLine("UsePAM " + _booleanFormatter.Format(UsePAM.Value));
  219. }
  220. writer.WriteLine("X11Forwarding " + _booleanFormatter.Format(X11Forwarding));
  221. foreach (var acceptedEnvVar in AcceptedEnvironmentVariables)
  222. {
  223. writer.WriteLine("AcceptEnv " + acceptedEnvVar);
  224. }
  225. if (Ciphers.Count > 0)
  226. {
  227. writer.WriteLine("Ciphers " + string.Join(",", Ciphers.Select(c => c.Name).ToArray()));
  228. }
  229. if (HostKeyAlgorithms.Count > 0)
  230. {
  231. writer.WriteLine("HostKeyAlgorithms " + string.Join(",", HostKeyAlgorithms.Select(c => c.Name).ToArray()));
  232. }
  233. if (KeyExchangeAlgorithms.Count > 0)
  234. {
  235. writer.WriteLine("KexAlgorithms " + string.Join(",", KeyExchangeAlgorithms.Select(c => c.Name).ToArray()));
  236. }
  237. if (MessageAuthenticationCodeAlgorithms.Count > 0)
  238. {
  239. writer.WriteLine("MACs " + string.Join(",", MessageAuthenticationCodeAlgorithms.Select(c => c.Name).ToArray()));
  240. }
  241. if (PublicKeyAcceptedAlgorithms.Count > 0)
  242. {
  243. writer.WriteLine("PubkeyAcceptedAlgorithms " + string.Join(",", PublicKeyAcceptedAlgorithms.Select(c => c.Name).ToArray()));
  244. }
  245. foreach (var match in Matches)
  246. {
  247. _matchFormatter.Format(match, writer);
  248. }
  249. }
  250. private static void ProcessGlobalOption(SshdConfig sshdConfig, string line)
  251. {
  252. var matchOptionRegex = new Regex(@"^\s*(?<name>[\S]+)\s+(?<value>.+?){1}\s*$");
  253. var optionsMatch = matchOptionRegex.Match(line);
  254. if (!optionsMatch.Success)
  255. {
  256. return;
  257. }
  258. var nameGroup = optionsMatch.Groups["name"];
  259. var valueGroup = optionsMatch.Groups["value"];
  260. var name = nameGroup.Value;
  261. var value = valueGroup.Value;
  262. switch (name)
  263. {
  264. case "Port":
  265. sshdConfig.Port = ToInt(value);
  266. break;
  267. case "HostKey":
  268. ParseCommaSeparatedValue(sshdConfig.HostKeyFiles, value);
  269. break;
  270. case "ChallengeResponseAuthentication":
  271. sshdConfig.ChallengeResponseAuthentication = ToBool(value);
  272. break;
  273. case "KbdInteractiveAuthentication":
  274. sshdConfig.KeyboardInteractiveAuthentication = ToBool(value);
  275. break;
  276. case "LogLevel":
  277. sshdConfig.LogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), value, ignoreCase: true);
  278. break;
  279. case "Subsystem":
  280. sshdConfig.Subsystems.Add(Subsystem.FromConfig(value));
  281. break;
  282. case "UsePAM":
  283. sshdConfig.UsePAM = ToBool(value);
  284. break;
  285. case "X11Forwarding":
  286. sshdConfig.X11Forwarding = ToBool(value);
  287. break;
  288. case "Ciphers":
  289. sshdConfig.Ciphers = ParseCiphers(value);
  290. break;
  291. case "KexAlgorithms":
  292. sshdConfig.KeyExchangeAlgorithms = ParseKeyExchangeAlgorithms(value);
  293. break;
  294. case "PubkeyAcceptedAlgorithms":
  295. sshdConfig.PublicKeyAcceptedAlgorithms = ParsePublicKeyAcceptedAlgorithms(value);
  296. break;
  297. case "HostKeyAlgorithms":
  298. sshdConfig.HostKeyAlgorithms = ParseHostKeyAlgorithms(value);
  299. break;
  300. case "MACs":
  301. sshdConfig.MessageAuthenticationCodeAlgorithms = ParseMacs(value);
  302. break;
  303. case "PrintMotd":
  304. sshdConfig.PrintMotd = ToBool(value);
  305. break;
  306. case "AcceptEnv":
  307. ParseAcceptedEnvironmentVariable(sshdConfig, value);
  308. break;
  309. case "Protocol":
  310. sshdConfig.Protocol = value;
  311. break;
  312. case "AllowTcpForwarding":
  313. sshdConfig.AllowTcpForwarding = ToBool(value);
  314. break;
  315. case "KeyRegenerationInterval":
  316. case "HostbasedAuthentication":
  317. case "ServerKeyBits":
  318. case "SyslogFacility":
  319. case "LoginGraceTime":
  320. case "PermitRootLogin":
  321. case "StrictModes":
  322. case "RSAAuthentication":
  323. case "PubkeyAuthentication":
  324. case "IgnoreRhosts":
  325. case "RhostsRSAAuthentication":
  326. case "PermitEmptyPasswords":
  327. case "X11DisplayOffset":
  328. case "PrintLastLog":
  329. case "TCPKeepAlive":
  330. case "AuthorizedKeysFile":
  331. case "PasswordAuthentication":
  332. case "GatewayPorts":
  333. break;
  334. default:
  335. throw new NotSupportedException($"Global option '{name}' is not supported.");
  336. }
  337. }
  338. private static void ParseAcceptedEnvironmentVariable(SshdConfig sshdConfig, string value)
  339. {
  340. var acceptedEnvironmentVariables = value.Split(' ');
  341. foreach (var acceptedEnvironmentVariable in acceptedEnvironmentVariables)
  342. {
  343. sshdConfig.AcceptedEnvironmentVariables.Add(acceptedEnvironmentVariable);
  344. }
  345. }
  346. private static List<Cipher> ParseCiphers(string value)
  347. {
  348. var cipherNames = value.Split(',');
  349. var ciphers = new List<Cipher>(cipherNames.Length);
  350. foreach (var cipherName in cipherNames)
  351. {
  352. ciphers.Add(new Cipher(cipherName.Trim()));
  353. }
  354. return ciphers;
  355. }
  356. private static List<KeyExchangeAlgorithm> ParseKeyExchangeAlgorithms(string value)
  357. {
  358. var kexNames = value.Split(',');
  359. var keyExchangeAlgorithms = new List<KeyExchangeAlgorithm>(kexNames.Length);
  360. foreach (var kexName in kexNames)
  361. {
  362. keyExchangeAlgorithms.Add(new KeyExchangeAlgorithm(kexName.Trim()));
  363. }
  364. return keyExchangeAlgorithms;
  365. }
  366. public static List<PublicKeyAlgorithm> ParsePublicKeyAcceptedAlgorithms(string value)
  367. {
  368. if (value is null)
  369. {
  370. throw new ArgumentNullException(nameof(value));
  371. }
  372. var publicKeyAlgorithmNames = value.Split(',');
  373. var publicKeyAlgorithms = new List<PublicKeyAlgorithm>(publicKeyAlgorithmNames.Length);
  374. foreach (var publicKeyAlgorithmName in publicKeyAlgorithmNames)
  375. {
  376. publicKeyAlgorithms.Add(new PublicKeyAlgorithm(publicKeyAlgorithmName.Trim()));
  377. }
  378. return publicKeyAlgorithms;
  379. }
  380. private static List<HostKeyAlgorithm> ParseHostKeyAlgorithms(string value)
  381. {
  382. var algorithmNames = value.Split(',');
  383. var hostKeyAlgorithms = new List<HostKeyAlgorithm>(algorithmNames.Length);
  384. foreach (var algorithmName in algorithmNames)
  385. {
  386. hostKeyAlgorithms.Add(new HostKeyAlgorithm(algorithmName.Trim()));
  387. }
  388. return hostKeyAlgorithms;
  389. }
  390. private static List<MessageAuthenticationCodeAlgorithm> ParseMacs(string value)
  391. {
  392. var macNames = value.Split(',');
  393. var macAlgorithms = new List<MessageAuthenticationCodeAlgorithm>(macNames.Length);
  394. foreach (var algorithmName in macNames)
  395. {
  396. macAlgorithms.Add(new MessageAuthenticationCodeAlgorithm(algorithmName.Trim()));
  397. }
  398. return macAlgorithms;
  399. }
  400. private static void ProcessMatchOption(Match matchConfiguration, string line)
  401. {
  402. var matchOptionRegex = new Regex(@"^\s+(?<name>[\S]+)\s+(?<value>.+?){1}\s*$");
  403. var optionsMatch = matchOptionRegex.Match(line);
  404. if (!optionsMatch.Success)
  405. {
  406. return;
  407. }
  408. var nameGroup = optionsMatch.Groups["name"];
  409. var valueGroup = optionsMatch.Groups["value"];
  410. var name = nameGroup.Value;
  411. var value = valueGroup.Value;
  412. switch (name)
  413. {
  414. case "AuthenticationMethods":
  415. matchConfiguration.AuthenticationMethods = value;
  416. break;
  417. default:
  418. throw new NotSupportedException($"Match option '{name}' is not supported.");
  419. }
  420. }
  421. private static void ParseCommaSeparatedValue(List<string> list, string value)
  422. {
  423. var values = value.Split(',');
  424. list.AddRange(values);
  425. }
  426. private static bool ToBool(string value)
  427. {
  428. switch (value)
  429. {
  430. case "yes":
  431. return true;
  432. case "no":
  433. return false;
  434. default:
  435. throw new ArgumentException($"Value '{value}' cannot be mapped to a boolean.",
  436. nameof(value));
  437. }
  438. }
  439. private static int ToInt(string value)
  440. {
  441. return int.Parse(value, NumberFormatInfo.InvariantInfo);
  442. }
  443. }
  444. }