SessionOptions.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. }
  18. [Guid("D924FAB9-FCE7-47B8-9F23-5717698384D3")]
  19. [ComVisible(true)]
  20. public enum FtpMode
  21. {
  22. Passive = 0,
  23. Active = 1,
  24. }
  25. [Guid("F2FC81EB-4761-4A4E-A3EC-4AFDD474C18C")]
  26. [ComVisible(true)]
  27. public enum FtpSecure
  28. {
  29. None = 0,
  30. Implicit = 1,
  31. Explicit = 3,
  32. [Obsolete("Use FtpSecure.Explicit")]
  33. ExplicitTls = Explicit,
  34. [Obsolete("Use FtpSecure.Explicit")]
  35. ExplicitSsl = 2,
  36. }
  37. [Guid("2D4EF368-EE80-4C15-AE77-D12AEAF4B00A")]
  38. [ClassInterface(Constants.ClassInterface)]
  39. [ComVisible(true)]
  40. public sealed class SessionOptions
  41. {
  42. public SessionOptions()
  43. {
  44. Timeout = new TimeSpan(0, 0, 15);
  45. RawSettings = new Dictionary<string,string>();
  46. }
  47. public Protocol Protocol { get; set; }
  48. public string HostName { get; set; }
  49. public int PortNumber { get { return _portNumber; } set { SetPortNumber(value); } }
  50. public string UserName { get; set; }
  51. public string Password { get { return GetPassword(); } set { SetPassword(value); } }
  52. public SecureString SecurePassword { get; set; }
  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. // SSH
  56. public string SshHostKeyFingerprint { get { return _sshHostKeyFingerprint; } set { SetSshHostKeyFingerprint(value); } }
  57. public bool GiveUpSecurityAndAcceptAnySshHostKey { get; set; }
  58. public string SshPrivateKeyPath { get; set; }
  59. public string SshPrivateKeyPassphrase { get; set; }
  60. // FTP
  61. public FtpMode FtpMode { get; set; }
  62. public FtpSecure FtpSecure { get; set; }
  63. // WebDAV
  64. public bool WebdavSecure { get; set; }
  65. public string WebdavRoot { get { return _webdavRoot; } set { SetWebdavRoot(value); } }
  66. // TLS
  67. public string TlsHostCertificateFingerprint { get { return _tlsHostCertificateFingerprint; } set { SetHostTlsCertificateFingerprint(value); } }
  68. public bool GiveUpSecurityAndAcceptAnyTlsHostCertificate { get; set; }
  69. public void AddRawSettings(string setting, string value)
  70. {
  71. RawSettings.Add(setting, value);
  72. }
  73. public void ParseUrl(string url)
  74. {
  75. url = url.Trim();
  76. const string protocolSeparator = "://";
  77. int index = url.IndexOf(protocolSeparator, StringComparison.OrdinalIgnoreCase);
  78. if (index < 0)
  79. {
  80. throw new ArgumentException("Protocol not specified", "url");
  81. }
  82. string protocol = url.Substring(0, index).Trim();
  83. FtpSecure = FtpSecure.None;
  84. if (protocol.Equals("sftp", StringComparison.OrdinalIgnoreCase))
  85. {
  86. Protocol = Protocol.Sftp;
  87. }
  88. else if (protocol.Equals("scp", StringComparison.OrdinalIgnoreCase))
  89. {
  90. Protocol = Protocol.Scp;
  91. }
  92. else if (protocol.Equals("ftp", StringComparison.OrdinalIgnoreCase))
  93. {
  94. Protocol = Protocol.Ftp;
  95. }
  96. else if (protocol.Equals("ftps", StringComparison.OrdinalIgnoreCase))
  97. {
  98. Protocol = Protocol.Ftp;
  99. FtpSecure = FtpSecure.Implicit;
  100. }
  101. else if (protocol.Equals("http", StringComparison.OrdinalIgnoreCase))
  102. {
  103. Protocol = Protocol.Webdav;
  104. }
  105. else if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
  106. {
  107. Protocol = Protocol.Webdav;
  108. WebdavSecure = true;
  109. }
  110. else
  111. {
  112. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unknown protocol {0}", protocol), "url");
  113. }
  114. url = url.Substring(index + protocolSeparator.Length).Trim();
  115. index = url.IndexOf('/');
  116. WebdavRoot = null;
  117. if (index >= 0)
  118. {
  119. string path = url.Substring(index).Trim();
  120. url = url.Substring(0, index).Trim();
  121. string parameters = path;
  122. path = CutToChar(ref parameters, ';');
  123. if (!string.IsNullOrEmpty(path) && (path != "/"))
  124. {
  125. if (Protocol != Protocol.Webdav)
  126. {
  127. throw new ArgumentException("Root folder can be specified for WebDAV protocol only", "url");
  128. }
  129. WebdavRoot = path;
  130. }
  131. // forward compatibility
  132. if (!string.IsNullOrEmpty(parameters))
  133. {
  134. throw new ArgumentException("No session parameters are supported", "url");
  135. }
  136. }
  137. index = url.LastIndexOf('@');
  138. string hostInfo;
  139. string userInfo = null;
  140. if (index >= 0)
  141. {
  142. userInfo = url.Substring(0, index).Trim();
  143. hostInfo = url.Substring(index + 1).Trim();
  144. }
  145. else
  146. {
  147. hostInfo = url;
  148. }
  149. PortNumber = 0;
  150. string portNumber = null;
  151. if ((hostInfo.Length >= 2) && (hostInfo[0] == '[') && ((index = hostInfo.IndexOf(']')) > 0))
  152. {
  153. HostName = hostInfo.Substring(1, index - 1).Trim();
  154. hostInfo = hostInfo.Substring(index + 1).Trim();
  155. if (hostInfo.Length > 0)
  156. {
  157. if (hostInfo[0] != ':')
  158. {
  159. throw new ArgumentException("Unexpected syntax after ]", "url");
  160. }
  161. else
  162. {
  163. portNumber = hostInfo.Substring(1);
  164. }
  165. }
  166. }
  167. else
  168. {
  169. HostName = UriUnescape(CutToChar(ref hostInfo, ':'));
  170. portNumber = hostInfo;
  171. }
  172. if (string.IsNullOrEmpty(HostName))
  173. {
  174. throw new ArgumentException("No host name", "url");
  175. }
  176. if (string.IsNullOrEmpty(portNumber))
  177. {
  178. PortNumber = 0;
  179. }
  180. else
  181. {
  182. portNumber = UriUnescape(portNumber);
  183. int number;
  184. if (!int.TryParse(portNumber, 0, CultureInfo.InvariantCulture, out number))
  185. {
  186. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} is not a valid port number", portNumber), "url");
  187. }
  188. else
  189. {
  190. PortNumber = number;
  191. }
  192. }
  193. UserName = null;
  194. Password = null;
  195. SshHostKeyFingerprint = null;
  196. GiveUpSecurityAndAcceptAnySshHostKey = false;
  197. TlsHostCertificateFingerprint = null;
  198. GiveUpSecurityAndAcceptAnyTlsHostCertificate = false;
  199. if (!string.IsNullOrEmpty(userInfo))
  200. {
  201. string parameters = userInfo;
  202. userInfo = CutToChar(ref parameters, ';');
  203. UserName = EmptyToNull(UriUnescape(CutToChar(ref userInfo, ':')));
  204. Password = EmptyToNull(UriUnescape(userInfo));
  205. while (!string.IsNullOrEmpty(parameters))
  206. {
  207. string parameter = CutToChar(ref parameters, ';');
  208. string parameterName = CutToChar(ref parameter, '=');
  209. if (parameterName.Equals("fingerprint", StringComparison.OrdinalIgnoreCase))
  210. {
  211. SshHostKeyFingerprint = parameter;
  212. }
  213. else
  214. {
  215. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported connection parameter {0}", parameterName), "url");
  216. }
  217. }
  218. }
  219. }
  220. private static string EmptyToNull(string s)
  221. {
  222. if (string.IsNullOrEmpty(s))
  223. {
  224. return null;
  225. }
  226. else
  227. {
  228. return s;
  229. }
  230. }
  231. private static string UriUnescape(string s)
  232. {
  233. return Uri.UnescapeDataString(s);
  234. }
  235. private static string CutToChar(ref string s, char c)
  236. {
  237. int index = s.IndexOf(c);
  238. string result;
  239. if (index >= 0)
  240. {
  241. result = s.Substring(0, index).Trim();
  242. s = s.Substring(index + 1).Trim();
  243. }
  244. else
  245. {
  246. result = s;
  247. s = string.Empty;
  248. }
  249. return result;
  250. }
  251. internal Dictionary<string, string> RawSettings { get; private set; }
  252. internal bool IsSsh { get { return (Protocol == Protocol.Sftp) || (Protocol == Protocol.Scp); } }
  253. private void SetSshHostKeyFingerprint(string s)
  254. {
  255. if (s != null)
  256. {
  257. Match match = _sshHostKeyRegex.Match(s);
  258. if (!match.Success || (match.Length != s.Length))
  259. {
  260. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "SSH host key fingerprint \"{0}\" does not match pattern /{1}/", s, _sshHostKeyRegex));
  261. }
  262. }
  263. _sshHostKeyFingerprint = s;
  264. }
  265. private void SetHostTlsCertificateFingerprint(string s)
  266. {
  267. if (s != null)
  268. {
  269. Match match = _tlsCertificateRegex.Match(s);
  270. if (!match.Success || (match.Length != s.Length))
  271. {
  272. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "TLS host certificate fingerprint \"{0}\" does not match pattern /{1}/", s, _tlsCertificateRegex));
  273. }
  274. }
  275. _tlsHostCertificateFingerprint = s;
  276. }
  277. private void SetTimeout(TimeSpan value)
  278. {
  279. if (value <= TimeSpan.Zero)
  280. {
  281. throw new ArgumentException("Timeout has to be positive non-zero value");
  282. }
  283. _timeout = value;
  284. }
  285. private void SetPortNumber(int value)
  286. {
  287. if (value < 0)
  288. {
  289. throw new ArgumentException("Port number cannot be negative");
  290. }
  291. _portNumber = value;
  292. }
  293. private void SetWebdavRoot(string value)
  294. {
  295. if (!string.IsNullOrEmpty(value) && (value[0] != '/'))
  296. {
  297. throw new ArgumentException("WebDAV root path has to start with slash");
  298. }
  299. _webdavRoot = value;
  300. }
  301. private void SetPassword(string value)
  302. {
  303. if (value == null)
  304. {
  305. SecurePassword = null;
  306. }
  307. else
  308. {
  309. SecurePassword = new SecureString();
  310. foreach (char c in value)
  311. {
  312. SecurePassword.AppendChar(c);
  313. }
  314. }
  315. }
  316. private string GetPassword()
  317. {
  318. if (SecurePassword == null)
  319. {
  320. return null;
  321. }
  322. else
  323. {
  324. IntPtr ptr = IntPtr.Zero;
  325. try
  326. {
  327. ptr = Marshal.SecureStringToGlobalAllocUnicode(SecurePassword);
  328. return Marshal.PtrToStringUni(ptr);
  329. }
  330. finally
  331. {
  332. Marshal.ZeroFreeGlobalAllocUnicode(ptr);
  333. }
  334. }
  335. }
  336. private string _sshHostKeyFingerprint;
  337. private string _tlsHostCertificateFingerprint;
  338. private TimeSpan _timeout;
  339. private int _portNumber;
  340. private string _webdavRoot;
  341. private const string _listPattern = @"{0}(;{0})*";
  342. private const string _sshHostKeyPattern = @"((ssh-rsa|ssh-dss)( |-))?(\d+ )?([0-9a-f]{2}(:|-)){15}[0-9a-f]{2}";
  343. private static readonly Regex _sshHostKeyRegex =
  344. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _sshHostKeyPattern));
  345. private const string _tlsCertificatePattern = @"([0-9a-f]{2}:){19}[0-9a-f]{2}";
  346. private static readonly Regex _tlsCertificateRegex =
  347. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _tlsCertificatePattern));
  348. }
  349. }