SessionOptions.cs 16 KB

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