SessionOptions.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. // Contrary to TSessionData::ParseUrl, not converting Webdav to S3 on S3 hostname.
  166. // Not sure if it is desirable and WinSCP will do the conversion for us later anyway.
  167. if (string.IsNullOrEmpty(HostName))
  168. {
  169. throw new ArgumentException("No host name", nameof(url));
  170. }
  171. if (string.IsNullOrEmpty(portNumber))
  172. {
  173. PortNumber = 0;
  174. }
  175. else
  176. {
  177. portNumber = UriUnescape(portNumber);
  178. if (!int.TryParse(portNumber, 0, CultureInfo.InvariantCulture, out int number))
  179. {
  180. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} is not a valid port number", portNumber), nameof(url));
  181. }
  182. else
  183. {
  184. PortNumber = number;
  185. }
  186. }
  187. UserName = null;
  188. Password = null;
  189. SshHostKeyFingerprint = null;
  190. SshHostKeyPolicy = SshHostKeyPolicy.Check;
  191. TlsHostCertificateFingerprint = null;
  192. GiveUpSecurityAndAcceptAnyTlsHostCertificate = false;
  193. if (!string.IsNullOrEmpty(userInfo))
  194. {
  195. string parameters = userInfo;
  196. userInfo = CutToChar(ref parameters, ';');
  197. bool hasPassword = (userInfo.IndexOf(':') >= 0);
  198. UserName = EmptyToNull(UriUnescape(CutToChar(ref userInfo, ':')));
  199. Password = hasPassword ? UriUnescape(userInfo) : null;
  200. while (!string.IsNullOrEmpty(parameters))
  201. {
  202. string parameter = CutToChar(ref parameters, ';');
  203. string parameterName = CutToChar(ref parameter, '=');
  204. parameter = UriUnescape(parameter);
  205. const string RawSettingsPrefix = "x-";
  206. if (parameterName.Equals("fingerprint", StringComparison.OrdinalIgnoreCase))
  207. {
  208. switch (Protocol)
  209. {
  210. case Protocol.Sftp:
  211. case Protocol.Scp:
  212. SshHostKeyFingerprint = parameter;
  213. break;
  214. case Protocol.Ftp:
  215. case Protocol.Webdav:
  216. case Protocol.S3:
  217. TlsHostCertificateFingerprint = parameter;
  218. break;
  219. default:
  220. throw new ArgumentException();
  221. }
  222. }
  223. else if (parameterName.StartsWith(RawSettingsPrefix, StringComparison.OrdinalIgnoreCase))
  224. {
  225. parameterName = UriUnescape(parameterName.Substring(RawSettingsPrefix.Length));
  226. if (parameterName.Equals("name", StringComparison.OrdinalIgnoreCase))
  227. {
  228. Name = parameter;
  229. }
  230. else
  231. {
  232. AddRawSettings(parameterName, parameter);
  233. }
  234. }
  235. else
  236. {
  237. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported connection parameter {0}", parameterName), nameof(url));
  238. }
  239. }
  240. }
  241. }
  242. private bool ParseProtocol(string protocol)
  243. {
  244. bool result = true;
  245. FtpSecure = FtpSecure.None;
  246. if (protocol.Equals("sftp", StringComparison.OrdinalIgnoreCase))
  247. {
  248. Protocol = Protocol.Sftp;
  249. }
  250. else if (protocol.Equals("scp", StringComparison.OrdinalIgnoreCase))
  251. {
  252. Protocol = Protocol.Scp;
  253. }
  254. else if (protocol.Equals("ftp", StringComparison.OrdinalIgnoreCase))
  255. {
  256. Protocol = Protocol.Ftp;
  257. }
  258. else if (protocol.Equals("ftps", StringComparison.OrdinalIgnoreCase))
  259. {
  260. Protocol = Protocol.Ftp;
  261. FtpSecure = FtpSecure.Implicit;
  262. }
  263. else if (protocol.Equals("ftpes", StringComparison.OrdinalIgnoreCase))
  264. {
  265. Protocol = Protocol.Ftp;
  266. FtpSecure = FtpSecure.Explicit;
  267. }
  268. else if (protocol.Equals("dav", StringComparison.OrdinalIgnoreCase) ||
  269. protocol.Equals("http", StringComparison.OrdinalIgnoreCase))
  270. {
  271. Protocol = Protocol.Webdav;
  272. }
  273. else if (protocol.Equals("davs", StringComparison.OrdinalIgnoreCase) ||
  274. protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
  275. {
  276. Protocol = Protocol.Webdav;
  277. WebdavSecure = true;
  278. }
  279. else if (protocol.Equals("s3", StringComparison.OrdinalIgnoreCase))
  280. {
  281. Protocol = Protocol.S3;
  282. }
  283. else
  284. {
  285. result = false;
  286. }
  287. return result;
  288. }
  289. private static string EmptyToNull(string s)
  290. {
  291. if (string.IsNullOrEmpty(s))
  292. {
  293. return null;
  294. }
  295. else
  296. {
  297. return s;
  298. }
  299. }
  300. private static string UriUnescape(string s)
  301. {
  302. return Uri.UnescapeDataString(s);
  303. }
  304. private static string CutToChar(ref string s, char c)
  305. {
  306. int index = s.IndexOf(c);
  307. string result;
  308. if (index >= 0)
  309. {
  310. result = s.Substring(0, index).Trim();
  311. s = s.Substring(index + 1).Trim();
  312. }
  313. else
  314. {
  315. result = s;
  316. s = string.Empty;
  317. }
  318. return result;
  319. }
  320. internal Dictionary<string, string> RawSettings { get; private set; }
  321. internal bool IsSsh { get { return (Protocol == Protocol.Sftp) || (Protocol == Protocol.Scp); } }
  322. internal bool IsTls { get { return GetIsTls(); } }
  323. private bool GetIsTls()
  324. {
  325. return
  326. ((Protocol == Protocol.Ftp) && (FtpSecure != FtpSecure.None)) ||
  327. ((Protocol == Protocol.Webdav) && WebdavSecure) ||
  328. (Protocol == Protocol.S3);
  329. }
  330. private void SetSshHostKeyFingerprint(string s)
  331. {
  332. if (s != null)
  333. {
  334. Match match = _sshHostKeyRegex.Match(s);
  335. if (!match.Success || (match.Length != s.Length))
  336. {
  337. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "SSH host key fingerprint \"{0}\" does not match pattern /{1}/", s, _sshHostKeyRegex));
  338. }
  339. }
  340. _sshHostKeyFingerprint = s;
  341. }
  342. private void SetHostTlsCertificateFingerprint(string s)
  343. {
  344. if (s != null)
  345. {
  346. Match match = _tlsCertificateRegex.Match(s);
  347. if (!match.Success || (match.Length != s.Length))
  348. {
  349. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "TLS host certificate fingerprint \"{0}\" does not match pattern /{1}/", s, _tlsCertificateRegex));
  350. }
  351. }
  352. _tlsHostCertificateFingerprint = s;
  353. }
  354. private void SetTimeout(TimeSpan value)
  355. {
  356. if (value <= TimeSpan.Zero)
  357. {
  358. throw new ArgumentException("Timeout has to be positive non-zero value");
  359. }
  360. _timeout = value;
  361. }
  362. private void SetPortNumber(int value)
  363. {
  364. if ((value < 0) || (value > 65535))
  365. {
  366. throw new ArgumentOutOfRangeException("Port number has to be in range from 0 to 65535");
  367. }
  368. _portNumber = value;
  369. }
  370. private void SetProtocol(Protocol value)
  371. {
  372. _protocol = value;
  373. if ((_protocol == Protocol.S3) && string.IsNullOrEmpty(HostName))
  374. {
  375. HostName = "s3.amazonaws.com";
  376. }
  377. }
  378. private void SetRootPath(string value)
  379. {
  380. if (!string.IsNullOrEmpty(value) && (value[0] != '/'))
  381. {
  382. throw new ArgumentException("Root path has to start with a slash");
  383. }
  384. _rootPath = value;
  385. }
  386. private static void SetPassword(ref SecureString securePassword, string value)
  387. {
  388. if (value == null)
  389. {
  390. securePassword = null;
  391. }
  392. else
  393. {
  394. securePassword = new SecureString();
  395. foreach (char c in value)
  396. {
  397. securePassword.AppendChar(c);
  398. }
  399. }
  400. }
  401. private static string GetPassword(SecureString securePassword)
  402. {
  403. if (securePassword == null)
  404. {
  405. return null;
  406. }
  407. else
  408. {
  409. IntPtr ptr = IntPtr.Zero;
  410. try
  411. {
  412. ptr = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
  413. return Marshal.PtrToStringUni(ptr);
  414. }
  415. finally
  416. {
  417. Marshal.ZeroFreeGlobalAllocUnicode(ptr);
  418. }
  419. }
  420. }
  421. private string GetName()
  422. {
  423. string result;
  424. if (_name != null)
  425. {
  426. result = _name;
  427. }
  428. else
  429. {
  430. if (!string.IsNullOrEmpty(HostName) && !string.IsNullOrEmpty(UserName))
  431. {
  432. result = $"{UserName}@{HostName}";
  433. }
  434. else if (!string.IsNullOrEmpty(HostName))
  435. {
  436. result = HostName;
  437. }
  438. else
  439. {
  440. result = "session";
  441. }
  442. }
  443. return result;
  444. }
  445. public override string ToString()
  446. {
  447. return Name;
  448. }
  449. private void SetGiveUpSecurityAndAcceptAnySshHostKey(bool value)
  450. {
  451. SshHostKeyPolicy = value ? SshHostKeyPolicy.GiveUpSecurityAndAcceptAny : SshHostKeyPolicy.Check;
  452. }
  453. private bool GetGiveUpSecurityAndAcceptAnySshHostKey()
  454. {
  455. return (SshHostKeyPolicy == SshHostKeyPolicy.GiveUpSecurityAndAcceptAny);
  456. }
  457. private SecureString _securePassword;
  458. private SecureString _secureNewPassword;
  459. private SecureString _securePrivateKeyPassphrase;
  460. private string _sshHostKeyFingerprint;
  461. private string _tlsHostCertificateFingerprint;
  462. private TimeSpan _timeout;
  463. private int _portNumber;
  464. private string _rootPath;
  465. private Protocol _protocol;
  466. private string _name;
  467. private const string _listPattern = @"{0}(;{0})*";
  468. 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}=?)";
  469. private static readonly Regex _sshHostKeyRegex =
  470. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _sshHostKeyPattern));
  471. private const string _tlsCertificatePattern = @"((([0-9a-fA-F]{2}[:\-]){31})|(([0-9a-fA-F]{2}[:\-]){19}))[0-9a-fA-F]{2}";
  472. private static readonly Regex _tlsCertificateRegex =
  473. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _tlsCertificatePattern));
  474. }
  475. }