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