1
0

SessionOptions.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using System.Text.RegularExpressions;
  5. using System.Globalization;
  6. using System.Security;
  7. namespace WinSCP
  8. {
  9. [Guid("F25C49A5-74A6-4E8F-AEB4-5B4E0DDF0EF9")]
  10. [ComVisible(true)]
  11. public enum Protocol
  12. {
  13. Sftp = 0,
  14. Scp = 1,
  15. Ftp = 2,
  16. Webdav = 3,
  17. S3 = 4,
  18. }
  19. [Guid("D924FAB9-FCE7-47B8-9F23-5717698384D3")]
  20. [ComVisible(true)]
  21. public enum FtpMode
  22. {
  23. Passive = 0,
  24. Active = 1,
  25. }
  26. [Guid("F2FC81EB-4761-4A4E-A3EC-4AFDD474C18C")]
  27. [ComVisible(true)]
  28. public enum FtpSecure
  29. {
  30. None = 0,
  31. Implicit = 1,
  32. Explicit = 3,
  33. }
  34. [Guid("8A98AB8F-30E8-4539-A3DE-A33DDC43B33C")]
  35. [ComVisible(true)]
  36. public enum SshHostKeyPolicy
  37. {
  38. Check = 0,
  39. GiveUpSecurityAndAcceptAny = 1,
  40. AcceptNew = 2,
  41. }
  42. [Guid("2D4EF368-EE80-4C15-AE77-D12AEAF4B00A")]
  43. [ClassInterface(Constants.ClassInterface)]
  44. [ComVisible(true)]
  45. public sealed class SessionOptions
  46. {
  47. public SessionOptions()
  48. {
  49. Timeout = new TimeSpan(0, 0, 15);
  50. RawSettings = new Dictionary<string,string>();
  51. }
  52. public string Name { get { return GetName(); } set { _name = value; } }
  53. public Protocol Protocol { get { return _protocol; } set { SetProtocol(value); } }
  54. public string HostName { get; set; }
  55. public int PortNumber { get { return _portNumber; } set { SetPortNumber(value); } }
  56. public string UserName { get; set; }
  57. public string Password { get { return GetPassword(_securePassword); } set { SetPassword(ref _securePassword, value); } }
  58. public SecureString SecurePassword { get { return _securePassword; } set { _securePassword = value; } }
  59. public string NewPassword { get { return GetPassword(_secureNewPassword); } set { SetPassword(ref _secureNewPassword, value); } }
  60. public SecureString SecureNewPassword { get { return _secureNewPassword; } set { _secureNewPassword = value; } }
  61. public TimeSpan Timeout { get { return _timeout; } set { SetTimeout(value); } }
  62. public int TimeoutInMilliseconds { get { return Tools.TimeSpanToMilliseconds(Timeout); } set { Timeout = Tools.MillisecondsToTimeSpan(value); } }
  63. public string PrivateKeyPassphrase { get { return GetPassword(_securePrivateKeyPassphrase); } set { SetPassword(ref _securePrivateKeyPassphrase, value); } }
  64. public SecureString SecurePrivateKeyPassphrase { get { return _securePrivateKeyPassphrase; } set { _securePrivateKeyPassphrase = value; } }
  65. public string RootPath { get { return _rootPath; } set { SetRootPath(value); } }
  66. // SSH
  67. public string SshHostKeyFingerprint { get { return _sshHostKeyFingerprint; } set { SetSshHostKeyFingerprint(value); } }
  68. public SshHostKeyPolicy SshHostKeyPolicy { get; set; }
  69. [Obsolete("Use SshHostKeyPolicy")]
  70. public bool GiveUpSecurityAndAcceptAnySshHostKey { get { return GetGiveUpSecurityAndAcceptAnySshHostKey(); } set { SetGiveUpSecurityAndAcceptAnySshHostKey(value); } }
  71. public string SshPrivateKeyPath { get; set; }
  72. [Obsolete("Use PrivateKeyPassphrase")]
  73. public string SshPrivateKeyPassphrase { get { return PrivateKeyPassphrase; } set { PrivateKeyPassphrase = value; } }
  74. // FTP
  75. public FtpMode FtpMode { get; set; }
  76. public FtpSecure FtpSecure { get; set; }
  77. // WebDAV
  78. public bool WebdavSecure { get; set; }
  79. [Obsolete("Use RootPath")]
  80. public string WebdavRoot { get { return RootPath; } set { RootPath = value; } }
  81. // TLS
  82. public string TlsHostCertificateFingerprint { get { return _tlsHostCertificateFingerprint; } set { SetHostTlsCertificateFingerprint(value); } }
  83. public bool GiveUpSecurityAndAcceptAnyTlsHostCertificate { get; set; }
  84. public string TlsClientCertificatePath { get; set; }
  85. public void AddRawSettings(string setting, string value)
  86. {
  87. RawSettings.Add(setting, value);
  88. }
  89. public void ParseUrl(string url)
  90. {
  91. if (url == null)
  92. {
  93. throw new ArgumentNullException(nameof(url));
  94. }
  95. url = url.Trim();
  96. const string protocolSeparator = "://";
  97. int index = url.IndexOf(protocolSeparator, StringComparison.OrdinalIgnoreCase);
  98. if (index < 0)
  99. {
  100. throw new ArgumentException("Protocol not specified", nameof(url));
  101. }
  102. string protocol = url.Substring(0, index).Trim();
  103. if (!ParseProtocol(protocol))
  104. {
  105. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unknown protocol {0}", protocol), nameof(url));
  106. }
  107. url = url.Substring(index + protocolSeparator.Length).Trim();
  108. index = url.IndexOf('/');
  109. RootPath = null;
  110. if (index >= 0)
  111. {
  112. string path = url.Substring(index).Trim();
  113. url = url.Substring(0, index).Trim();
  114. string parameters = path;
  115. path = CutToChar(ref parameters, ';');
  116. if (!string.IsNullOrEmpty(path) && (path != "/"))
  117. {
  118. if ((Protocol != Protocol.Webdav) && (Protocol != Protocol.S3))
  119. {
  120. throw new ArgumentException("Root path can be specified for WebDAV and S3 protocols only", nameof(url));
  121. }
  122. RootPath = path;
  123. }
  124. // forward compatibility
  125. if (!string.IsNullOrEmpty(parameters))
  126. {
  127. throw new ArgumentException("No session parameters are supported", nameof(url));
  128. }
  129. }
  130. index = url.LastIndexOf('@');
  131. string hostInfo;
  132. string userInfo = null;
  133. if (index >= 0)
  134. {
  135. userInfo = url.Substring(0, index).Trim();
  136. hostInfo = url.Substring(index + 1).Trim();
  137. }
  138. else
  139. {
  140. hostInfo = url;
  141. }
  142. PortNumber = 0;
  143. string portNumber = null;
  144. if ((hostInfo.Length >= 2) && (hostInfo[0] == '[') && ((index = hostInfo.IndexOf(']')) > 0))
  145. {
  146. HostName = hostInfo.Substring(1, index - 1).Trim();
  147. hostInfo = hostInfo.Substring(index + 1).Trim();
  148. if (hostInfo.Length > 0)
  149. {
  150. if (hostInfo[0] != ':')
  151. {
  152. throw new ArgumentException("Unexpected syntax after ]", nameof(url));
  153. }
  154. else
  155. {
  156. portNumber = hostInfo.Substring(1);
  157. }
  158. }
  159. }
  160. else
  161. {
  162. HostName = UriUnescape(CutToChar(ref hostInfo, ':'));
  163. portNumber = hostInfo;
  164. }
  165. if (string.IsNullOrEmpty(HostName))
  166. {
  167. throw new ArgumentException("No host name", nameof(url));
  168. }
  169. if (string.IsNullOrEmpty(portNumber))
  170. {
  171. PortNumber = 0;
  172. }
  173. else
  174. {
  175. portNumber = UriUnescape(portNumber);
  176. if (!int.TryParse(portNumber, 0, CultureInfo.InvariantCulture, out int number))
  177. {
  178. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} is not a valid port number", portNumber), nameof(url));
  179. }
  180. else
  181. {
  182. PortNumber = number;
  183. }
  184. }
  185. UserName = null;
  186. Password = null;
  187. SshHostKeyFingerprint = null;
  188. SshHostKeyPolicy = SshHostKeyPolicy.Check;
  189. TlsHostCertificateFingerprint = null;
  190. GiveUpSecurityAndAcceptAnyTlsHostCertificate = false;
  191. if (!string.IsNullOrEmpty(userInfo))
  192. {
  193. string parameters = userInfo;
  194. userInfo = CutToChar(ref parameters, ';');
  195. bool hasPassword = (userInfo.IndexOf(':') >= 0);
  196. UserName = EmptyToNull(UriUnescape(CutToChar(ref userInfo, ':')));
  197. Password = hasPassword ? UriUnescape(userInfo) : null;
  198. while (!string.IsNullOrEmpty(parameters))
  199. {
  200. string parameter = CutToChar(ref parameters, ';');
  201. string parameterName = CutToChar(ref parameter, '=');
  202. parameter = UriUnescape(parameter);
  203. const string RawSettingsPrefix = "x-";
  204. if (parameterName.Equals("fingerprint", StringComparison.OrdinalIgnoreCase))
  205. {
  206. switch (Protocol)
  207. {
  208. case Protocol.Sftp:
  209. case Protocol.Scp:
  210. SshHostKeyFingerprint = parameter;
  211. break;
  212. case Protocol.Ftp:
  213. case Protocol.Webdav:
  214. case Protocol.S3:
  215. TlsHostCertificateFingerprint = parameter;
  216. break;
  217. default:
  218. throw new ArgumentException();
  219. }
  220. }
  221. else if (parameterName.StartsWith(RawSettingsPrefix, StringComparison.OrdinalIgnoreCase))
  222. {
  223. parameterName = UriUnescape(parameterName.Substring(RawSettingsPrefix.Length));
  224. if (parameterName.Equals("name", StringComparison.OrdinalIgnoreCase))
  225. {
  226. Name = parameter;
  227. }
  228. else
  229. {
  230. AddRawSettings(parameterName, parameter);
  231. }
  232. }
  233. else
  234. {
  235. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported connection parameter {0}", parameterName), nameof(url));
  236. }
  237. }
  238. }
  239. }
  240. private bool ParseProtocol(string protocol)
  241. {
  242. bool result = true;
  243. FtpSecure = FtpSecure.None;
  244. if (protocol.Equals("sftp", StringComparison.OrdinalIgnoreCase))
  245. {
  246. Protocol = Protocol.Sftp;
  247. }
  248. else if (protocol.Equals("scp", StringComparison.OrdinalIgnoreCase))
  249. {
  250. Protocol = Protocol.Scp;
  251. }
  252. else if (protocol.Equals("ftp", StringComparison.OrdinalIgnoreCase))
  253. {
  254. Protocol = Protocol.Ftp;
  255. }
  256. else if (protocol.Equals("ftps", StringComparison.OrdinalIgnoreCase))
  257. {
  258. Protocol = Protocol.Ftp;
  259. FtpSecure = FtpSecure.Implicit;
  260. }
  261. else if (protocol.Equals("ftpes", StringComparison.OrdinalIgnoreCase))
  262. {
  263. Protocol = Protocol.Ftp;
  264. FtpSecure = FtpSecure.Explicit;
  265. }
  266. else if (protocol.Equals("dav", StringComparison.OrdinalIgnoreCase) ||
  267. protocol.Equals("http", StringComparison.OrdinalIgnoreCase))
  268. {
  269. Protocol = Protocol.Webdav;
  270. }
  271. else if (protocol.Equals("davs", StringComparison.OrdinalIgnoreCase) ||
  272. protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
  273. {
  274. Protocol = Protocol.Webdav;
  275. WebdavSecure = true;
  276. }
  277. else if (protocol.Equals("s3", StringComparison.OrdinalIgnoreCase))
  278. {
  279. Protocol = Protocol.S3;
  280. }
  281. else
  282. {
  283. result = false;
  284. }
  285. return result;
  286. }
  287. private static string EmptyToNull(string s)
  288. {
  289. if (string.IsNullOrEmpty(s))
  290. {
  291. return null;
  292. }
  293. else
  294. {
  295. return s;
  296. }
  297. }
  298. private static string UriUnescape(string s)
  299. {
  300. return Uri.UnescapeDataString(s);
  301. }
  302. private static string CutToChar(ref string s, char c)
  303. {
  304. int index = s.IndexOf(c);
  305. string result;
  306. if (index >= 0)
  307. {
  308. result = s.Substring(0, index).Trim();
  309. s = s.Substring(index + 1).Trim();
  310. }
  311. else
  312. {
  313. result = s;
  314. s = string.Empty;
  315. }
  316. return result;
  317. }
  318. internal Dictionary<string, string> RawSettings { get; private set; }
  319. internal bool IsSsh { get { return (Protocol == Protocol.Sftp) || (Protocol == Protocol.Scp); } }
  320. internal bool IsTls { get { return GetIsTls(); } }
  321. private bool GetIsTls()
  322. {
  323. return
  324. ((Protocol == Protocol.Ftp) && (FtpSecure != FtpSecure.None)) ||
  325. ((Protocol == Protocol.Webdav) && WebdavSecure) ||
  326. (Protocol == Protocol.S3);
  327. }
  328. private void SetSshHostKeyFingerprint(string s)
  329. {
  330. if (s != null)
  331. {
  332. Match match = _sshHostKeyRegex.Match(s);
  333. if (!match.Success || (match.Length != s.Length))
  334. {
  335. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "SSH host key fingerprint \"{0}\" does not match pattern /{1}/", s, _sshHostKeyRegex));
  336. }
  337. }
  338. _sshHostKeyFingerprint = s;
  339. }
  340. private void SetHostTlsCertificateFingerprint(string s)
  341. {
  342. if (s != null)
  343. {
  344. Match match = _tlsCertificateRegex.Match(s);
  345. if (!match.Success || (match.Length != s.Length))
  346. {
  347. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "TLS host certificate fingerprint \"{0}\" does not match pattern /{1}/", s, _tlsCertificateRegex));
  348. }
  349. }
  350. _tlsHostCertificateFingerprint = s;
  351. }
  352. private void SetTimeout(TimeSpan value)
  353. {
  354. if (value <= TimeSpan.Zero)
  355. {
  356. throw new ArgumentException("Timeout has to be positive non-zero value");
  357. }
  358. _timeout = value;
  359. }
  360. private void SetPortNumber(int value)
  361. {
  362. if ((value < 0) || (value > 65535))
  363. {
  364. throw new ArgumentOutOfRangeException("Port number has to be in range from 0 to 65535");
  365. }
  366. _portNumber = value;
  367. }
  368. private void SetProtocol(Protocol value)
  369. {
  370. _protocol = value;
  371. if ((_protocol == Protocol.S3) && string.IsNullOrEmpty(HostName))
  372. {
  373. HostName = "s3.amazonaws.com";
  374. }
  375. }
  376. private void SetRootPath(string value)
  377. {
  378. if (!string.IsNullOrEmpty(value) && (value[0] != '/'))
  379. {
  380. throw new ArgumentException("Root path has to start with a slash");
  381. }
  382. _rootPath = value;
  383. }
  384. private static void SetPassword(ref SecureString securePassword, string value)
  385. {
  386. if (value == null)
  387. {
  388. securePassword = null;
  389. }
  390. else
  391. {
  392. securePassword = new SecureString();
  393. foreach (char c in value)
  394. {
  395. securePassword.AppendChar(c);
  396. }
  397. }
  398. }
  399. private static string GetPassword(SecureString securePassword)
  400. {
  401. if (securePassword == null)
  402. {
  403. return null;
  404. }
  405. else
  406. {
  407. IntPtr ptr = IntPtr.Zero;
  408. try
  409. {
  410. ptr = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
  411. return Marshal.PtrToStringUni(ptr);
  412. }
  413. finally
  414. {
  415. Marshal.ZeroFreeGlobalAllocUnicode(ptr);
  416. }
  417. }
  418. }
  419. private string GetName()
  420. {
  421. string result;
  422. if (_name != null)
  423. {
  424. result = _name;
  425. }
  426. else
  427. {
  428. if (!string.IsNullOrEmpty(HostName) && !string.IsNullOrEmpty(UserName))
  429. {
  430. result = $"{UserName}@{HostName}";
  431. }
  432. else if (!string.IsNullOrEmpty(HostName))
  433. {
  434. result = HostName;
  435. }
  436. else
  437. {
  438. result = "session";
  439. }
  440. }
  441. return result;
  442. }
  443. public override string ToString()
  444. {
  445. return Name;
  446. }
  447. private void SetGiveUpSecurityAndAcceptAnySshHostKey(bool value)
  448. {
  449. SshHostKeyPolicy = value ? SshHostKeyPolicy.GiveUpSecurityAndAcceptAny : SshHostKeyPolicy.Check;
  450. }
  451. private bool GetGiveUpSecurityAndAcceptAnySshHostKey()
  452. {
  453. return (SshHostKeyPolicy == SshHostKeyPolicy.GiveUpSecurityAndAcceptAny);
  454. }
  455. private SecureString _securePassword;
  456. private SecureString _secureNewPassword;
  457. private SecureString _securePrivateKeyPassphrase;
  458. private string _sshHostKeyFingerprint;
  459. private string _tlsHostCertificateFingerprint;
  460. private TimeSpan _timeout;
  461. private int _portNumber;
  462. private string _rootPath;
  463. private Protocol _protocol;
  464. private string _name;
  465. private const string _listPattern = @"{0}(;{0})*";
  466. private const string _sshHostKeyPattern = @"((ssh-rsa|ssh-dss|ssh-ed25519|ecdsa-sha2-nistp(256|384|521))( |-))?(\d+ )?(([0-9a-fA-F]{2}(:|-)){15}[0-9a-fA-F]{2}|[0-9a-zA-Z+/\-_]{43}=?)";
  467. private static readonly Regex _sshHostKeyRegex =
  468. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _sshHostKeyPattern));
  469. private const string _tlsCertificatePattern = @"((([0-9a-fA-F]{2}[:\-]){31})|(([0-9a-fA-F]{2}[:\-]){19}))[0-9a-fA-F]{2}";
  470. private static readonly Regex _tlsCertificateRegex =
  471. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _tlsCertificatePattern));
  472. }
  473. }