2
0

SshdConfig.cs 21 KB

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