PageRenderTime 52ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/SharpSSH/jsch/Util.cs

https://bitbucket.org/sign42/sharpssh
C# | 593 lines | 480 code | 43 blank | 70 comment | 99 complexity | 92c41af0755f96787a9f9d93f5ae55b2 MD5 | raw file
  1. using System;
  2. using System.Collections;
  3. using System.Text;
  4. using System.Threading;
  5. using Tamir.SharpSsh.java;
  6. using Tamir.SharpSsh.java.net;
  7. namespace Tamir.SharpSsh.jsch
  8. {
  9. /* -*-mode:java; c-basic-offset:2; -*- */
  10. /*
  11. Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.
  12. Redistribution and use in source and binary forms, with or without
  13. modification, are permitted provided that the following conditions are met:
  14. 1. Redistributions of source code must retain the above copyright notice,
  15. this list of conditions and the following disclaimer.
  16. 2. Redistributions in binary form must reproduce the above copyright
  17. notice, this list of conditions and the following disclaimer in
  18. the documentation and/or other materials provided with the distribution.
  19. 3. The names of the authors may not be used to endorse or promote products
  20. derived from this software without specific prior written permission.
  21. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  22. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  23. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  24. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  25. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  27. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  28. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  30. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. public class Util
  33. {
  34. /// <summary>
  35. /// Converts a time_t to DateTime
  36. /// </summary>
  37. public static DateTime Time_T2DateTime(uint time_t)
  38. {
  39. long win32FileTime = 10000000*(long) time_t + 116444736000000000;
  40. return DateTime.FromFileTimeUtc(win32FileTime).ToLocalTime();
  41. }
  42. private static byte[] b64 = Encoding.Default.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=");
  43. private static byte val(byte foo)
  44. {
  45. if (foo == '=') return 0;
  46. for (int j = 0; j < b64.Length; j++)
  47. {
  48. if (foo == b64[j]) return (byte) j;
  49. }
  50. return 0;
  51. }
  52. internal static byte[] fromBase64(byte[] buf, int start, int length)
  53. {
  54. byte[] foo = new byte[length];
  55. int j = 0;
  56. int l = length;
  57. for (int i = start; i < start + length; i += 4)
  58. {
  59. foo[j] = (byte) ((val(buf[i]) << 2) | ((val(buf[i + 1]) & 0x30) >> 4));
  60. if (buf[i + 2] == (byte) '=')
  61. {
  62. j++;
  63. break;
  64. }
  65. foo[j + 1] = (byte) (((val(buf[i + 1]) & 0x0f) << 4) | ((val(buf[i + 2]) & 0x3c) >> 2));
  66. if (buf[i + 3] == (byte) '=')
  67. {
  68. j += 2;
  69. break;
  70. }
  71. foo[j + 2] = (byte) (((val(buf[i + 2]) & 0x03) << 6) | (val(buf[i + 3]) & 0x3f));
  72. j += 3;
  73. }
  74. byte[] bar = new byte[j];
  75. Array.Copy(foo, 0, bar, 0, j);
  76. return bar;
  77. }
  78. internal static byte[] toBase64(byte[] buf, int start, int length)
  79. {
  80. byte[] tmp = new byte[length*2];
  81. int i, j, k;
  82. int foo = (length/3)*3 + start;
  83. i = 0;
  84. for (j = start; j < foo; j += 3)
  85. {
  86. k = (buf[j] >> 2) & 0x3f;
  87. tmp[i++] = b64[k];
  88. k = (buf[j] & 0x03) << 4 | (buf[j + 1] >> 4) & 0x0f;
  89. tmp[i++] = b64[k];
  90. k = (buf[j + 1] & 0x0f) << 2 | (buf[j + 2] >> 6) & 0x03;
  91. tmp[i++] = b64[k];
  92. k = buf[j + 2] & 0x3f;
  93. tmp[i++] = b64[k];
  94. }
  95. foo = (start + length) - foo;
  96. if (foo == 1)
  97. {
  98. k = (buf[j] >> 2) & 0x3f;
  99. tmp[i++] = b64[k];
  100. k = ((buf[j] & 0x03) << 4) & 0x3f;
  101. tmp[i++] = b64[k];
  102. tmp[i++] = (byte) '=';
  103. tmp[i++] = (byte) '=';
  104. }
  105. else if (foo == 2)
  106. {
  107. k = (buf[j] >> 2) & 0x3f;
  108. tmp[i++] = b64[k];
  109. k = (buf[j] & 0x03) << 4 | (buf[j + 1] >> 4) & 0x0f;
  110. tmp[i++] = b64[k];
  111. k = ((buf[j + 1] & 0x0f) << 2) & 0x3f;
  112. tmp[i++] = b64[k];
  113. tmp[i++] = (byte) '=';
  114. }
  115. byte[] bar = new byte[i];
  116. Array.Copy(tmp, 0, bar, 0, i);
  117. return bar;
  118. // return sun.misc.BASE64Encoder().encode(buf);
  119. }
  120. internal static String[] split(String foo, String split)
  121. {
  122. byte[] buf = getBytes(foo);
  123. ArrayList bar = new ArrayList();
  124. int start = 0;
  125. int index;
  126. while (true)
  127. {
  128. index = foo.IndexOf(split, start);
  129. if (index >= 0)
  130. {
  131. bar.Add(getString(buf, start, index - start));
  132. start = index + 1;
  133. continue;
  134. }
  135. bar.Add(getString(buf, start, buf.Length - start));
  136. break;
  137. }
  138. String[] result = new String[bar.Count];
  139. for (int i = 0; i < result.Length; i++)
  140. {
  141. result[i] = (String) (bar[i]);
  142. }
  143. return result;
  144. }
  145. internal static bool glob(byte[] pattern, byte[] name)
  146. {
  147. return glob(pattern, 0, name, 0);
  148. }
  149. private static bool glob(byte[] pattern, int pattern_index,
  150. byte[] name, int name_index)
  151. {
  152. //System.out.println("glob: "+new String(pattern)+", "+new String(name));
  153. int patternlen = pattern.Length;
  154. if (patternlen == 0)
  155. return false;
  156. int namelen = name.Length;
  157. int i = pattern_index;
  158. int j = name_index;
  159. while (i < patternlen && j < namelen)
  160. {
  161. if (pattern[i] == '\\')
  162. {
  163. if (i + 1 == patternlen)
  164. return false;
  165. i++;
  166. if (pattern[i] != name[j]) return false;
  167. i++;
  168. j++;
  169. continue;
  170. }
  171. if (pattern[i] == '*')
  172. {
  173. if (patternlen == i + 1) return true;
  174. i++;
  175. byte foo = pattern[i];
  176. while (j < namelen)
  177. {
  178. if (foo == name[j])
  179. {
  180. if (glob(pattern, i, name, j))
  181. {
  182. return true;
  183. }
  184. }
  185. j++;
  186. }
  187. return false;
  188. /*
  189. if(j==namelen) return false;
  190. i++; j++;
  191. continue;
  192. */
  193. }
  194. if (pattern[i] == '?')
  195. {
  196. i++;
  197. j++;
  198. continue;
  199. }
  200. if (pattern[i] != name[j]) return false;
  201. i++;
  202. j++;
  203. continue;
  204. }
  205. if (i == patternlen && j == namelen) return true;
  206. return false;
  207. }
  208. private static String[] chars = {
  209. "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
  210. };
  211. internal static String getFingerPrint(HASH hash, byte[] data)
  212. {
  213. try
  214. {
  215. hash.init();
  216. hash.update(data, 0, data.Length);
  217. byte[] foo = hash.digest();
  218. StringBuilder sb = new StringBuilder();
  219. uint bar;
  220. for (int i = 0; i < foo.Length; i++)
  221. {
  222. bar = (byte) (foo[i] & 0xff);
  223. sb.Append(chars[(bar >> 4) & 0xf]);
  224. sb.Append(chars[(bar) & 0xf]);
  225. if (i + 1 < foo.Length)
  226. sb.Append(":");
  227. }
  228. return sb.ToString();
  229. }
  230. catch
  231. {
  232. return "???";
  233. }
  234. }
  235. internal static Socket createSocket(String host, int port, int timeout)
  236. {
  237. Socket socket = null;
  238. String message = "";
  239. if (timeout == 0)
  240. {
  241. try
  242. {
  243. socket = new Socket(host, port);
  244. return socket;
  245. }
  246. catch (Exception e)
  247. {
  248. message = e.ToString();
  249. throw new JSchException(message);
  250. }
  251. }
  252. String _host = host;
  253. int _port = port;
  254. Socket[] sockp = new Socket[1];
  255. Thread currentThread = Thread.CurrentThread;
  256. Exception[] ee = new Exception[1];
  257. message = "";
  258. createSocketRun runnable = new createSocketRun(sockp, ee, _host, _port);
  259. Thread tmp = new Thread(new ThreadStart(runnable.run));
  260. tmp.Name = "Opening Socket " + host;
  261. tmp.Start();
  262. try
  263. {
  264. tmp.Join(timeout);
  265. message = "timeout: ";
  266. }
  267. catch (ThreadInterruptedException eee)
  268. {
  269. }
  270. if (sockp[0] != null && sockp[0].isConnected())
  271. {
  272. socket = sockp[0];
  273. }
  274. else
  275. {
  276. message += "socket is not established";
  277. if (ee[0] != null)
  278. {
  279. message = ee[0].ToString();
  280. }
  281. tmp.Interrupt();
  282. tmp = null;
  283. throw new JSchException(message);
  284. }
  285. return socket;
  286. }
  287. private class createSocketRun
  288. {
  289. private Socket[] sockp;
  290. private Exception[] ee;
  291. private string _host;
  292. private int _port;
  293. public createSocketRun(Socket[] sockp, Exception[] ee, string _host, int _port)
  294. {
  295. this.sockp = sockp;
  296. this.ee = ee;
  297. this._host = _host;
  298. this._port = _port;
  299. }
  300. public void run()
  301. {
  302. sockp[0] = null;
  303. try
  304. {
  305. sockp[0] = new Socket(_host, _port);
  306. }
  307. catch (Exception e)
  308. {
  309. ee[0] = e;
  310. if (sockp[0] != null && sockp[0].isConnected())
  311. {
  312. try
  313. {
  314. sockp[0].Close();
  315. }
  316. catch (Exception eee)
  317. {
  318. }
  319. }
  320. sockp[0] = null;
  321. }
  322. }
  323. }
  324. internal static bool array_equals(byte[] foo, byte[] bar)
  325. {
  326. int i = foo.Length;
  327. if (i != bar.Length) return false;
  328. for (int j = 0; j < i; j++)
  329. {
  330. if (foo[j] != bar[j]) return false;
  331. }
  332. //try{while(true){i--; if(foo[i]!=bar[i])return false;}}catch(System.Exception e){}
  333. return true;
  334. }
  335. public static string getString(byte[] arr, int offset, int len)
  336. {
  337. return Encoding.Default.GetString(arr, offset, len);
  338. }
  339. public static string getStringUTF8(byte[] arr, int offset, int len)
  340. {
  341. return Encoding.UTF8.GetString(arr, offset, len);
  342. }
  343. public static string getString(byte[] arr)
  344. {
  345. return getString(arr, 0, arr.Length);
  346. }
  347. public static string getStringUTF8(byte[] arr)
  348. {
  349. return getStringUTF8(arr, 0, arr.Length);
  350. }
  351. public static byte[] getBytes(String str)
  352. {
  353. return Encoding.Default.GetBytes(str);
  354. }
  355. public static byte[] getBytesUTF8(String str)
  356. {
  357. return Encoding.UTF8.GetBytes(str);
  358. }
  359. public static bool regionMatches(String orig, bool ignoreCase, int toffset,
  360. String other, int ooffset, int len)
  361. {
  362. char[] ta = new char[orig.Length];
  363. char[] pa = new char[other.Length];
  364. orig.CopyTo(0, ta, 0, orig.Length);
  365. int to = toffset;
  366. other.CopyTo(0, pa, 0, other.Length);
  367. int po = ooffset;
  368. // Note: toffset, ooffset, or len might be near -1>>>1.
  369. if ((ooffset < 0) || (toffset < 0) || (toffset > (long) orig.Length - len) ||
  370. (ooffset > (long) other.Length - len))
  371. {
  372. return false;
  373. }
  374. while (len-- > 0)
  375. {
  376. char c1 = ta[to++];
  377. char c2 = pa[po++];
  378. if (c1 == c2)
  379. {
  380. continue;
  381. }
  382. if (ignoreCase)
  383. {
  384. // If characters don't match but case may be ignored,
  385. // try converting both characters to uppercase.
  386. // If the results match, then the comparison scan should
  387. // continue.
  388. char u1 = char.ToUpper(c1);
  389. char u2 = char.ToUpper(c2);
  390. if (u1 == u2)
  391. {
  392. continue;
  393. }
  394. // Unfortunately, conversion to uppercase does not work properly
  395. // for the Georgian alphabet, which has strange rules about case
  396. // conversion. So we need to make one last check before
  397. // exiting.
  398. if (char.ToLower(u1) == char.ToLower(u2))
  399. {
  400. continue;
  401. }
  402. }
  403. return false;
  404. }
  405. return true;
  406. }
  407. public static uint ToUInt32(byte[] ptr, int Index)
  408. {
  409. uint ui = 0;
  410. ui = ((uint) ptr[Index++]) << 24;
  411. ui += ((uint) ptr[Index++]) << 16;
  412. ui += ((uint) ptr[Index++]) << 8;
  413. ui += (uint) ptr[Index++];
  414. return ui;
  415. }
  416. public static int ToInt32(byte[] ptr, int Index)
  417. {
  418. return (int) ToUInt32(ptr, Index);
  419. }
  420. public static ushort ToUInt16(byte[] ptr, int Index)
  421. {
  422. ushort u = 0;
  423. u = (ushort) ptr[Index++];
  424. u *= 256;
  425. u += (ushort) ptr[Index++];
  426. return u;
  427. }
  428. public static bool ArrayContains(Object[] arr, Object o)
  429. {
  430. for (int i = 0; i < arr.Length; i++)
  431. {
  432. if (arr[i].Equals(o))
  433. return true;
  434. }
  435. return false;
  436. }
  437. public static bool ArrayContains(char[] arr, char c)
  438. {
  439. for (int i = 0; i < arr.Length; i++)
  440. {
  441. if (arr[i] == c)
  442. return true;
  443. }
  444. return false;
  445. }
  446. public static bool ArrayContains(char[] arr, char c, int count)
  447. {
  448. for (int i = 0; i < count; i++)
  449. {
  450. if (arr[i] == c)
  451. return true;
  452. }
  453. return false;
  454. }
  455. /**
  456. * Utility method to delete the leading zeros from the modulus.
  457. * @param a modulus
  458. * @return modulus
  459. */
  460. public static byte[] stripLeadingZeros(byte[] a)
  461. {
  462. int lastZero = -1;
  463. for (int i = 0; i < a.Length; i++)
  464. {
  465. if (a[i] == 0)
  466. {
  467. lastZero = i;
  468. }
  469. else
  470. {
  471. break;
  472. }
  473. }
  474. lastZero++;
  475. byte[] result = new byte[a.Length - lastZero];
  476. Array.Copy(a, lastZero, result, 0, result.Length);
  477. return result;
  478. }
  479. /*
  480. Based on: http://www.orlingrabbe.com/dsa_java.htm
  481. And on: http://groups.google.com/group/comp.lang.java.security/browse_thread/thread/8f3bb93f9348434f/a1681ec252084483?lnk=st&q=ASN.1+signature+dsa+format&rnum=5&hl=en#a1681ec252084483
  482. If you're asking about the SHA/DSA signature format from
  483. java.security.Signature, it looks like this, for example:
  484. % od -tx1 sig
  485. 0000000 30 2c 02 14 4f 01 01 92 24 7c b3 c7 af 76 71 92
  486. 0000020 9c db c7 fe 1f 4e 42 4f 02 14 78 f3 63 d5 a3 0e
  487. 0000040 be 7d 92 7c 43 8d 0f 5f 02 df ee 35 9e b2
  488. It's DER format, with 0x30 meaning SEQUENCE, 0x2c the length of the
  489. sequence, 0x02 meaning INTEGER, and 0x14 the length of the integer.
  490. The first integer (as a byte array) is r, and the second one is s.
  491. */
  492. public static byte[] FixDsaSig(byte[] sig)
  493. {
  494. byte[] newSig = new byte[40];
  495. Array.Copy(sig, 4, newSig, 0, 20);
  496. int index;
  497. if (sig.Length == 46)
  498. index = 26;
  499. else if (sig.Length == 47)
  500. index = 27;
  501. else
  502. throw new Exception("Can't fix DSA Signature.");
  503. Array.Copy(sig, index, newSig, 20, 20);
  504. return newSig;
  505. }
  506. public static string hex(byte[] arr)
  507. {
  508. string hex = "0x";
  509. for (int i = 0; i < arr.Length; i++)
  510. {
  511. string mbyte = arr[i].ToString("X");
  512. if (mbyte.Length == 1)
  513. mbyte = "0" + mbyte;
  514. hex += mbyte;
  515. }
  516. return hex;
  517. }
  518. internal static String unquote(String _path)
  519. {
  520. byte[] path = _path.GetBytes();
  521. int pathlen = path.Length;
  522. int i = 0;
  523. while (i < pathlen)
  524. {
  525. if (path[i] == '\\')
  526. {
  527. if (i + 1 == pathlen)
  528. break;
  529. Array.Copy(path, i + 1, path, i, path.Length - (i + 1));
  530. pathlen--;
  531. continue;
  532. }
  533. i++;
  534. }
  535. if (pathlen == path.Length) return _path;
  536. byte[] foo = new byte[pathlen];
  537. Array.Copy(path, 0, foo, 0, pathlen);
  538. return new JavaString(foo);
  539. }
  540. }
  541. }