SessionOptions.cs 19 KB

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