SessionOptions.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. UserName = EmptyToNull(UriUnescape(CutToChar(ref userInfo, ':')));
  183. Password = EmptyToNull(UriUnescape(userInfo));
  184. while (!string.IsNullOrEmpty(parameters))
  185. {
  186. string parameter = CutToChar(ref parameters, ';');
  187. string parameterName = CutToChar(ref parameter, '=');
  188. if (parameterName.Equals("fingerprint", StringComparison.OrdinalIgnoreCase))
  189. {
  190. SshHostKeyFingerprint = parameter;
  191. }
  192. else
  193. {
  194. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported connection parameter {0}", parameterName), "url");
  195. }
  196. }
  197. }
  198. }
  199. private bool ParseProtocol(string protocol)
  200. {
  201. bool result = true;
  202. FtpSecure = FtpSecure.None;
  203. if (protocol.Equals("sftp", StringComparison.OrdinalIgnoreCase))
  204. {
  205. Protocol = Protocol.Sftp;
  206. }
  207. else if (protocol.Equals("scp", StringComparison.OrdinalIgnoreCase))
  208. {
  209. Protocol = Protocol.Scp;
  210. }
  211. else if (protocol.Equals("ftp", StringComparison.OrdinalIgnoreCase))
  212. {
  213. Protocol = Protocol.Ftp;
  214. }
  215. else if (protocol.Equals("ftps", StringComparison.OrdinalIgnoreCase))
  216. {
  217. Protocol = Protocol.Ftp;
  218. FtpSecure = FtpSecure.Implicit;
  219. }
  220. else if (protocol.Equals("ftpes", StringComparison.OrdinalIgnoreCase))
  221. {
  222. Protocol = Protocol.Ftp;
  223. FtpSecure = FtpSecure.Explicit;
  224. }
  225. else if (protocol.Equals("dav", StringComparison.OrdinalIgnoreCase) ||
  226. protocol.Equals("http", StringComparison.OrdinalIgnoreCase))
  227. {
  228. Protocol = Protocol.Webdav;
  229. }
  230. else if (protocol.Equals("davs", StringComparison.OrdinalIgnoreCase) ||
  231. protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
  232. {
  233. Protocol = Protocol.Webdav;
  234. WebdavSecure = true;
  235. }
  236. else if (protocol.Equals("s3", StringComparison.OrdinalIgnoreCase))
  237. {
  238. Protocol = Protocol.S3;
  239. }
  240. else
  241. {
  242. result = false;
  243. }
  244. return result;
  245. }
  246. private static string EmptyToNull(string s)
  247. {
  248. if (string.IsNullOrEmpty(s))
  249. {
  250. return null;
  251. }
  252. else
  253. {
  254. return s;
  255. }
  256. }
  257. private static string UriUnescape(string s)
  258. {
  259. return Uri.UnescapeDataString(s);
  260. }
  261. private static string CutToChar(ref string s, char c)
  262. {
  263. int index = s.IndexOf(c);
  264. string result;
  265. if (index >= 0)
  266. {
  267. result = s.Substring(0, index).Trim();
  268. s = s.Substring(index + 1).Trim();
  269. }
  270. else
  271. {
  272. result = s;
  273. s = string.Empty;
  274. }
  275. return result;
  276. }
  277. internal Dictionary<string, string> RawSettings { get; private set; }
  278. internal bool IsSsh { get { return (Protocol == Protocol.Sftp) || (Protocol == Protocol.Scp); } }
  279. internal bool IsTls { get { return GetIsTls(); } }
  280. private bool GetIsTls()
  281. {
  282. return
  283. ((Protocol == Protocol.Ftp) && (FtpSecure != FtpSecure.None)) ||
  284. ((Protocol == Protocol.Webdav) && WebdavSecure) ||
  285. (Protocol == Protocol.S3);
  286. }
  287. private void SetSshHostKeyFingerprint(string s)
  288. {
  289. if (s != null)
  290. {
  291. Match match = _sshHostKeyRegex.Match(s);
  292. if (!match.Success || (match.Length != s.Length))
  293. {
  294. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "SSH host key fingerprint \"{0}\" does not match pattern /{1}/", s, _sshHostKeyRegex));
  295. }
  296. }
  297. _sshHostKeyFingerprint = s;
  298. }
  299. private void SetHostTlsCertificateFingerprint(string s)
  300. {
  301. if (s != null)
  302. {
  303. Match match = _tlsCertificateRegex.Match(s);
  304. if (!match.Success || (match.Length != s.Length))
  305. {
  306. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "TLS host certificate fingerprint \"{0}\" does not match pattern /{1}/", s, _tlsCertificateRegex));
  307. }
  308. }
  309. _tlsHostCertificateFingerprint = s;
  310. }
  311. private void SetTimeout(TimeSpan value)
  312. {
  313. if (value <= TimeSpan.Zero)
  314. {
  315. throw new ArgumentException("Timeout has to be positive non-zero value");
  316. }
  317. _timeout = value;
  318. }
  319. private void SetPortNumber(int value)
  320. {
  321. if (value < 0)
  322. {
  323. throw new ArgumentException("Port number cannot be negative");
  324. }
  325. _portNumber = value;
  326. }
  327. private void SetProtocol(Protocol value)
  328. {
  329. _protocol = value;
  330. if ((_protocol == Protocol.S3) && string.IsNullOrEmpty(HostName))
  331. {
  332. HostName = "s3.amazonaws.com";
  333. }
  334. }
  335. private void SetWebdavRoot(string value)
  336. {
  337. if (!string.IsNullOrEmpty(value) && (value[0] != '/'))
  338. {
  339. throw new ArgumentException("WebDAV root path has to start with slash");
  340. }
  341. _webdavRoot = value;
  342. }
  343. private static void SetPassword(ref SecureString securePassword, string value)
  344. {
  345. if (value == null)
  346. {
  347. securePassword = null;
  348. }
  349. else
  350. {
  351. securePassword = new SecureString();
  352. foreach (char c in value)
  353. {
  354. securePassword.AppendChar(c);
  355. }
  356. }
  357. }
  358. private static string GetPassword(SecureString securePassword)
  359. {
  360. if (securePassword == null)
  361. {
  362. return null;
  363. }
  364. else
  365. {
  366. IntPtr ptr = IntPtr.Zero;
  367. try
  368. {
  369. ptr = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
  370. return Marshal.PtrToStringUni(ptr);
  371. }
  372. finally
  373. {
  374. Marshal.ZeroFreeGlobalAllocUnicode(ptr);
  375. }
  376. }
  377. }
  378. private SecureString _securePassword;
  379. private SecureString _secureNewPassword;
  380. private SecureString _securePrivateKeyPassphrase;
  381. private string _sshHostKeyFingerprint;
  382. private string _tlsHostCertificateFingerprint;
  383. private TimeSpan _timeout;
  384. private int _portNumber;
  385. private string _webdavRoot;
  386. private Protocol _protocol;
  387. private const string _listPattern = @"{0}(;{0})*";
  388. 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}";
  389. private static readonly Regex _sshHostKeyRegex =
  390. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _sshHostKeyPattern));
  391. private const string _tlsCertificatePattern = @"([0-9a-f]{2}:){19}[0-9a-f]{2}";
  392. private static readonly Regex _tlsCertificateRegex =
  393. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _tlsCertificatePattern));
  394. }
  395. }