SessionOptions.cs 18 KB

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