SessionOptions.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 { return GetPassword(_securePrivateKeyPassphrase); } set { SetPassword(ref _securePrivateKeyPassphrase, value); } }
  54. public SecureString SecurePrivateKeyPassphrase { get { return _securePrivateKeyPassphrase; } set { _securePrivateKeyPassphrase = 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. [Obsolete("Use PrivateKeyPassphrase")]
  60. public string SshPrivateKeyPassphrase { get { return PrivateKeyPassphrase; } set { PrivateKeyPassphrase = value; } }
  61. // FTP
  62. public FtpMode FtpMode { get; set; }
  63. public FtpSecure FtpSecure { get; set; }
  64. // WebDAV
  65. public bool WebdavSecure { get; set; }
  66. public string WebdavRoot { get { return _webdavRoot; } set { SetWebdavRoot(value); } }
  67. // TLS
  68. public string TlsHostCertificateFingerprint { get { return _tlsHostCertificateFingerprint; } set { SetHostTlsCertificateFingerprint(value); } }
  69. public bool GiveUpSecurityAndAcceptAnyTlsHostCertificate { get; set; }
  70. public string TlsClientCertificatePath { get; set; }
  71. public void AddRawSettings(string setting, string value)
  72. {
  73. RawSettings.Add(setting, value);
  74. }
  75. public void ParseUrl(string url)
  76. {
  77. if (url == null)
  78. {
  79. throw new ArgumentNullException("url");
  80. }
  81. url = url.Trim();
  82. const string protocolSeparator = "://";
  83. int index = url.IndexOf(protocolSeparator, StringComparison.OrdinalIgnoreCase);
  84. if (index < 0)
  85. {
  86. throw new ArgumentException("Protocol not specified", "url");
  87. }
  88. string protocol = url.Substring(0, index).Trim();
  89. if (!ParseProtocol(protocol))
  90. {
  91. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unknown protocol {0}", protocol), "url");
  92. }
  93. url = url.Substring(index + protocolSeparator.Length).Trim();
  94. index = url.IndexOf('/');
  95. WebdavRoot = null;
  96. if (index >= 0)
  97. {
  98. string path = url.Substring(index).Trim();
  99. url = url.Substring(0, index).Trim();
  100. string parameters = path;
  101. path = CutToChar(ref parameters, ';');
  102. if (!string.IsNullOrEmpty(path) && (path != "/"))
  103. {
  104. if (Protocol != Protocol.Webdav)
  105. {
  106. throw new ArgumentException("Root folder can be specified for WebDAV protocol only", "url");
  107. }
  108. WebdavRoot = path;
  109. }
  110. // forward compatibility
  111. if (!string.IsNullOrEmpty(parameters))
  112. {
  113. throw new ArgumentException("No session parameters are supported", "url");
  114. }
  115. }
  116. index = url.LastIndexOf('@');
  117. string hostInfo;
  118. string userInfo = null;
  119. if (index >= 0)
  120. {
  121. userInfo = url.Substring(0, index).Trim();
  122. hostInfo = url.Substring(index + 1).Trim();
  123. }
  124. else
  125. {
  126. hostInfo = url;
  127. }
  128. PortNumber = 0;
  129. string portNumber = null;
  130. if ((hostInfo.Length >= 2) && (hostInfo[0] == '[') && ((index = hostInfo.IndexOf(']')) > 0))
  131. {
  132. HostName = hostInfo.Substring(1, index - 1).Trim();
  133. hostInfo = hostInfo.Substring(index + 1).Trim();
  134. if (hostInfo.Length > 0)
  135. {
  136. if (hostInfo[0] != ':')
  137. {
  138. throw new ArgumentException("Unexpected syntax after ]", "url");
  139. }
  140. else
  141. {
  142. portNumber = hostInfo.Substring(1);
  143. }
  144. }
  145. }
  146. else
  147. {
  148. HostName = UriUnescape(CutToChar(ref hostInfo, ':'));
  149. portNumber = hostInfo;
  150. }
  151. if (string.IsNullOrEmpty(HostName))
  152. {
  153. throw new ArgumentException("No host name", "url");
  154. }
  155. if (string.IsNullOrEmpty(portNumber))
  156. {
  157. PortNumber = 0;
  158. }
  159. else
  160. {
  161. portNumber = UriUnescape(portNumber);
  162. int number;
  163. if (!int.TryParse(portNumber, 0, CultureInfo.InvariantCulture, out 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
  237. {
  238. result = false;
  239. }
  240. return result;
  241. }
  242. private static string EmptyToNull(string s)
  243. {
  244. if (string.IsNullOrEmpty(s))
  245. {
  246. return null;
  247. }
  248. else
  249. {
  250. return s;
  251. }
  252. }
  253. private static string UriUnescape(string s)
  254. {
  255. return Uri.UnescapeDataString(s);
  256. }
  257. private static string CutToChar(ref string s, char c)
  258. {
  259. int index = s.IndexOf(c);
  260. string result;
  261. if (index >= 0)
  262. {
  263. result = s.Substring(0, index).Trim();
  264. s = s.Substring(index + 1).Trim();
  265. }
  266. else
  267. {
  268. result = s;
  269. s = string.Empty;
  270. }
  271. return result;
  272. }
  273. internal Dictionary<string, string> RawSettings { get; private set; }
  274. internal bool IsSsh { get { return (Protocol == Protocol.Sftp) || (Protocol == Protocol.Scp); } }
  275. internal bool IsTls { get { return GetIsTls(); } }
  276. private bool GetIsTls()
  277. {
  278. return
  279. ((Protocol == Protocol.Ftp) && (FtpSecure != FtpSecure.None)) ||
  280. ((Protocol == Protocol.Webdav) && WebdavSecure);
  281. }
  282. private void SetSshHostKeyFingerprint(string s)
  283. {
  284. if (s != null)
  285. {
  286. Match match = _sshHostKeyRegex.Match(s);
  287. if (!match.Success || (match.Length != s.Length))
  288. {
  289. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "SSH host key fingerprint \"{0}\" does not match pattern /{1}/", s, _sshHostKeyRegex));
  290. }
  291. }
  292. _sshHostKeyFingerprint = s;
  293. }
  294. private void SetHostTlsCertificateFingerprint(string s)
  295. {
  296. if (s != null)
  297. {
  298. Match match = _tlsCertificateRegex.Match(s);
  299. if (!match.Success || (match.Length != s.Length))
  300. {
  301. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "TLS host certificate fingerprint \"{0}\" does not match pattern /{1}/", s, _tlsCertificateRegex));
  302. }
  303. }
  304. _tlsHostCertificateFingerprint = s;
  305. }
  306. private void SetTimeout(TimeSpan value)
  307. {
  308. if (value <= TimeSpan.Zero)
  309. {
  310. throw new ArgumentException("Timeout has to be positive non-zero value");
  311. }
  312. _timeout = value;
  313. }
  314. private void SetPortNumber(int value)
  315. {
  316. if (value < 0)
  317. {
  318. throw new ArgumentException("Port number cannot be negative");
  319. }
  320. _portNumber = value;
  321. }
  322. private void SetWebdavRoot(string value)
  323. {
  324. if (!string.IsNullOrEmpty(value) && (value[0] != '/'))
  325. {
  326. throw new ArgumentException("WebDAV root path has to start with slash");
  327. }
  328. _webdavRoot = value;
  329. }
  330. private static void SetPassword(ref SecureString securePassword, string value)
  331. {
  332. if (value == null)
  333. {
  334. securePassword = null;
  335. }
  336. else
  337. {
  338. securePassword = new SecureString();
  339. foreach (char c in value)
  340. {
  341. securePassword.AppendChar(c);
  342. }
  343. }
  344. }
  345. private static string GetPassword(SecureString securePassword)
  346. {
  347. if (securePassword == null)
  348. {
  349. return null;
  350. }
  351. else
  352. {
  353. IntPtr ptr = IntPtr.Zero;
  354. try
  355. {
  356. ptr = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
  357. return Marshal.PtrToStringUni(ptr);
  358. }
  359. finally
  360. {
  361. Marshal.ZeroFreeGlobalAllocUnicode(ptr);
  362. }
  363. }
  364. }
  365. private SecureString _securePassword;
  366. private SecureString _secureNewPassword;
  367. private SecureString _securePrivateKeyPassphrase;
  368. private string _sshHostKeyFingerprint;
  369. private string _tlsHostCertificateFingerprint;
  370. private TimeSpan _timeout;
  371. private int _portNumber;
  372. private string _webdavRoot;
  373. private const string _listPattern = @"{0}(;{0})*";
  374. 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}";
  375. private static readonly Regex _sshHostKeyRegex =
  376. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _sshHostKeyPattern));
  377. private const string _tlsCertificatePattern = @"([0-9a-f]{2}:){19}[0-9a-f]{2}";
  378. private static readonly Regex _tlsCertificateRegex =
  379. new Regex(string.Format(CultureInfo.InvariantCulture, _listPattern, _tlsCertificatePattern));
  380. }
  381. }