SessionOptions.cs 18 KB

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