SessionOptions.cs 20 KB

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