SessionOptions.cs 14 KB

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