SessionOptions.cs 15 KB

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