SSH.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. package de.tudarmstadt.informatik.hostage.protocol;
  2. import java.math.BigInteger;
  3. import java.nio.ByteBuffer;
  4. import java.security.KeyFactory;
  5. import java.security.KeyPair;
  6. import java.security.KeyPairGenerator;
  7. import java.security.MessageDigest;
  8. import java.security.PublicKey;
  9. import java.security.Signature;
  10. import java.security.interfaces.DSAPublicKey;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.Random;
  14. import javax.crypto.KeyAgreement;
  15. import javax.crypto.interfaces.DHPublicKey;
  16. import javax.crypto.spec.DHParameterSpec;
  17. import javax.crypto.spec.DHPublicKeySpec;
  18. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  19. import de.tudarmstadt.informatik.hostage.wrapper.ByteArray;
  20. /**
  21. * SSH protocol.
  22. * @author Wulf Pfeiffer
  23. */
  24. public final class SSH implements Protocol<ByteArray> {
  25. /**
  26. * Represents the states of the protocol.
  27. */
  28. private enum STATE {
  29. NONE,
  30. SERVER_VERSION,
  31. CLIENT_VERSION,
  32. KEX_INIT,
  33. CLOSED
  34. }
  35. /**
  36. * Denotes in which state the protocol is right now.
  37. */
  38. private STATE connectionState = STATE.NONE;
  39. private String serverVersion = "SSH-2.0-";
  40. private String serverType = "OpenSSH_6.0p1 Debian-4";
  41. //Diffie-Hellman-Group-1 p and g
  42. private final byte[] p = {
  43. (byte)0x00,
  44. (byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,
  45. (byte)0xC9,(byte)0x0F,(byte)0xDA,(byte)0xA2,(byte)0x21,(byte)0x68,(byte)0xC2,(byte)0x34,
  46. (byte)0xC4,(byte)0xC6,(byte)0x62,(byte)0x8B,(byte)0x80,(byte)0xDC,(byte)0x1C,(byte)0xD1,
  47. (byte)0x29,(byte)0x02,(byte)0x4E,(byte)0x08,(byte)0x8A,(byte)0x67,(byte)0xCC,(byte)0x74,
  48. (byte)0x02,(byte)0x0B,(byte)0xBE,(byte)0xA6,(byte)0x3B,(byte)0x13,(byte)0x9B,(byte)0x22,
  49. (byte)0x51,(byte)0x4A,(byte)0x08,(byte)0x79,(byte)0x8E,(byte)0x34,(byte)0x04,(byte)0xDD,
  50. (byte)0xEF,(byte)0x95,(byte)0x19,(byte)0xB3,(byte)0xCD,(byte)0x3A,(byte)0x43,(byte)0x1B,
  51. (byte)0x30,(byte)0x2B,(byte)0x0A,(byte)0x6D,(byte)0xF2,(byte)0x5F,(byte)0x14,(byte)0x37,
  52. (byte)0x4F,(byte)0xE1,(byte)0x35,(byte)0x6D,(byte)0x6D,(byte)0x51,(byte)0xC2,(byte)0x45,
  53. (byte)0xE4,(byte)0x85,(byte)0xB5,(byte)0x76,(byte)0x62,(byte)0x5E,(byte)0x7E,(byte)0xC6,
  54. (byte)0xF4,(byte)0x4C,(byte)0x42,(byte)0xE9,(byte)0xA6,(byte)0x37,(byte)0xED,(byte)0x6B,
  55. (byte)0x0B,(byte)0xFF,(byte)0x5C,(byte)0xB6,(byte)0xF4,(byte)0x06,(byte)0xB7,(byte)0xED,
  56. (byte)0xEE,(byte)0x38,(byte)0x6B,(byte)0xFB,(byte)0x5A,(byte)0x89,(byte)0x9F,(byte)0xA5,
  57. (byte)0xAE,(byte)0x9F,(byte)0x24,(byte)0x11,(byte)0x7C,(byte)0x4B,(byte)0x1F,(byte)0xE6,
  58. (byte)0x49,(byte)0x28,(byte)0x66,(byte)0x51,(byte)0xEC,(byte)0xE6,(byte)0x53,(byte)0x81,
  59. (byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF
  60. };
  61. private final byte[] g = {0x02};
  62. //SSH Parameters for Kex etc.
  63. private byte[] V_S = serverType.getBytes();
  64. private byte[] V_C;
  65. private byte[] I_S;
  66. private byte[] I_C;
  67. private byte[] e;
  68. private byte[] f;
  69. private byte[] k;
  70. private byte[] h;
  71. private byte[] K_S;
  72. private byte[] sig;
  73. //Keys for signature
  74. private KeyPair dsa;
  75. //allowed algorithms for kexinit
  76. private String kex_alg = "diffie-hellman-group1-sha1";
  77. private String server_alg = "ssh-dss";
  78. private String encrypt_alg_c = "aes128-ctr";
  79. private String encrypt_alg_s = "aes128-ctr";
  80. private String mac_alg_c = "hmac-sha1";
  81. private String mac_alg_s = "hmac-sha1";
  82. private String comp_alg_c = "none";
  83. private String comp_alg_s = "none";
  84. private int cipherBlockSize = 16;
  85. /** Denotes in which state the protocol is right now */
  86. private STATE state = STATE.NONE;
  87. private byte[] lastMessage;
  88. @Override
  89. public int getPort() {
  90. return 22;
  91. }
  92. @Override
  93. public TALK_FIRST whoTalksFirst() {
  94. return TALK_FIRST.SERVER;
  95. }
  96. @Override
  97. public List<ByteArray> processMessage(ByteArray message) {
  98. if(message != null)
  99. lastMessage = message.get();
  100. List<ByteArray> response = new ArrayList<ByteArray>();
  101. byte[] request = null;
  102. if(message != null) request = message.get();
  103. switch(connectionState) {
  104. case NONE:
  105. response.add(new ByteArray(serverVersion + serverType + "\r\n"));
  106. connectionState = STATE.SERVER_VERSION;
  107. break;
  108. case SERVER_VERSION:
  109. extractType(request);
  110. extractCookie(request);
  111. response.add(new ByteArray(kexInit()));
  112. connectionState = STATE.CLIENT_VERSION;
  113. break;
  114. case CLIENT_VERSION:
  115. extractPubKey(request);
  116. response.add(new ByteArray(dhKexReply()));
  117. //FIXME signature in dhKexReply is wrong, don't know why
  118. response.add(new ByteArray(newKeys()));
  119. connectionState = STATE.KEX_INIT;
  120. break;
  121. case KEX_INIT:
  122. connectionState = STATE.CLOSED;
  123. break;
  124. case CLOSED:
  125. break;
  126. default:
  127. connectionState = STATE.CLOSED;
  128. break;
  129. }
  130. return response;
  131. }
  132. @Override
  133. public boolean isClosed() {
  134. return (state == STATE.CLOSED);
  135. }
  136. @Override
  137. public boolean isSecure() {
  138. return false;
  139. }
  140. @Override
  141. public Class<ByteArray> getType() {
  142. return ByteArray.class;
  143. }
  144. @Override
  145. public String toString() {
  146. return "SSH";
  147. }
  148. @Override
  149. public String getRequestContent() {
  150. return HelperUtils.byteToStr(lastMessage);
  151. }
  152. /**
  153. * Wraps the packets with packet length and padding.
  154. * @param packet content that is wrapped.
  155. * @return wrapped packet.
  156. */
  157. private byte[] wrapPacket(byte[] packet) {
  158. int packetLength = 5 + packet.length; //4 byte packet length, 1 byte padding length, payload length
  159. int paddingLengthCBS = cipherBlockSize - (packetLength % cipherBlockSize);
  160. int paddingLength8 = 8 - (packetLength % 8);
  161. int paddingLength = paddingLengthCBS > paddingLength8 ? paddingLengthCBS : paddingLength8;
  162. if(paddingLength < 4) paddingLength += cipherBlockSize;
  163. packetLength = packetLength + paddingLength - 4; //add padding string length to packet length
  164. byte[] packetLen = ByteBuffer.allocate(4).putInt(packetLength).array();
  165. byte[] paddingLen = {(byte) paddingLength};
  166. byte[] paddingString = new byte[paddingLength];
  167. for(int i = 0; i < paddingLength; i++) {
  168. paddingString[i] = 0x00;
  169. }
  170. return HelperUtils.concat(packetLen, paddingLen, packet, paddingString);
  171. }
  172. /**
  173. * Builds the Kex Init packet that contains all the allowed algorithms by the server.
  174. * @return Kex Init packet.
  175. */
  176. private byte[] kexInit() {
  177. byte[] msgCode = {0x14};
  178. I_S = randomBytes(16);
  179. byte[] kexLength = ByteBuffer.allocate(4).putInt(kex_alg.getBytes().length).array();
  180. byte[] serverLength = ByteBuffer.allocate(4).putInt(server_alg.getBytes().length).array();
  181. byte[] encrypt_c_Length = ByteBuffer.allocate(4).putInt(encrypt_alg_c.getBytes().length).array();
  182. byte[] encrypt_s_Length = ByteBuffer.allocate(4).putInt(encrypt_alg_s.getBytes().length).array();
  183. byte[] mac_c_Length = ByteBuffer.allocate(4).putInt(mac_alg_c.getBytes().length).array();
  184. byte[] mac_s_Length = ByteBuffer.allocate(4).putInt(mac_alg_s.getBytes().length).array();
  185. byte[] comp_c_Length = ByteBuffer.allocate(4).putInt(comp_alg_c.getBytes().length).array();
  186. byte[] comp_s_Length = ByteBuffer.allocate(4).putInt(comp_alg_s.getBytes().length).array();
  187. byte[] language_c_s = {0x00, 0x00, 0x00, 0x00};
  188. byte[] language_s_c = {0x00, 0x00, 0x00, 0x00};
  189. byte[] kexFirsPckt = {0x00};
  190. byte[] reserved = {0x00, 0x00, 0x00, 0x00};
  191. byte[] response = HelperUtils.concat(msgCode, I_S, kexLength, kex_alg.getBytes(), serverLength, server_alg.getBytes(),
  192. encrypt_c_Length, encrypt_alg_c.getBytes(), encrypt_s_Length, encrypt_alg_s.getBytes(), mac_c_Length, mac_alg_c.getBytes(),
  193. mac_s_Length, mac_alg_s.getBytes(), comp_c_Length, comp_alg_c.getBytes(), comp_s_Length, comp_alg_s.getBytes(),
  194. language_c_s, language_s_c, kexFirsPckt, reserved);
  195. return wrapPacket(response);
  196. }
  197. /**
  198. * Builds the Diffie-Hellman Kex Reply, containing the host key,f and the signature.
  199. * @return Diffie-Hellman Kex Reply packet.
  200. */
  201. private byte[] dhKexReply() {
  202. generateDHKeys();
  203. generateHostKey();
  204. generateSha1Hash();
  205. generateSignature();
  206. byte[] msgCode = {0x1f};
  207. byte[] hostKeyLength = ByteBuffer.allocate(4).putInt(K_S.length).array();
  208. byte[] fDHLength = ByteBuffer.allocate(4).putInt(f.length).array();
  209. byte[] signatureLength = ByteBuffer.allocate(4).putInt(sig.length).array();
  210. byte[] server_algLength = ByteBuffer.allocate(4).putInt(server_alg.getBytes().length).array();
  211. byte[] payloadLength = ByteBuffer.allocate(4).putInt(server_algLength.length + signatureLength.length + sig.length + server_alg.getBytes().length).array();
  212. byte[] response = HelperUtils.concat(msgCode, hostKeyLength, K_S,
  213. fDHLength, f, payloadLength, server_algLength, server_alg.getBytes(), signatureLength, sig);
  214. return wrapPacket(response);
  215. }
  216. /**
  217. * New Keys response.
  218. * @return New Keys response.
  219. */
  220. private byte[] newKeys() {
  221. byte[] msgCode = {0x15};
  222. return wrapPacket(msgCode);
  223. }
  224. /**
  225. * Generates the required Diffie-Hellman keys with p and g from Oakley Group 1.
  226. */
  227. private void generateDHKeys() {
  228. try {
  229. KeyPairGenerator myKpairGen = KeyPairGenerator.getInstance("DH");
  230. KeyAgreement myKeyAgree = KeyAgreement.getInstance("DH");
  231. BigInteger p = new BigInteger(this.p);
  232. BigInteger g = new BigInteger(this.g);
  233. BigInteger e = new BigInteger(this.e);
  234. DHParameterSpec dhParamSpec = new DHParameterSpec(p, g);
  235. myKpairGen.initialize(dhParamSpec);
  236. KeyPair myKpair = myKpairGen.generateKeyPair();
  237. myKeyAgree.init(myKpair.getPrivate());
  238. BigInteger f = ((DHPublicKey) (myKpair.getPublic())).getY();
  239. this.f = f.toByteArray();
  240. KeyFactory myKeyFac = KeyFactory.getInstance("DH");
  241. DHPublicKeySpec keySpec = new DHPublicKeySpec(e, p, g);
  242. PublicKey yourPubKey = myKeyFac.generatePublic(keySpec);
  243. myKeyAgree.doPhase(yourPubKey, true);
  244. byte[] mySharedSecret = myKeyAgree.generateSecret();
  245. k = mySharedSecret;
  246. } catch (Exception e) {
  247. e.printStackTrace();
  248. }
  249. }
  250. /**
  251. * Generates the Host Key based on the DSA algorithm
  252. */
  253. private void generateHostKey() {
  254. try {
  255. KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA");
  256. dsa = generator.generateKeyPair();
  257. byte[] string = "ssh-dss".getBytes();
  258. byte[] stringLength = ByteBuffer.allocate(4).putInt(string.length).array();
  259. byte[] p = ((DSAPublicKey) dsa.getPublic()).getParams().getP().toByteArray();
  260. if(p[0] != 0x00) p = HelperUtils.concat(new byte[]{0x00}, p);
  261. byte[] pLength = ByteBuffer.allocate(4).putInt(p.length).array();
  262. byte[] q = ((DSAPublicKey) dsa.getPublic()).getParams().getQ().toByteArray();
  263. if(q[0] != 0x00) q = HelperUtils.concat(new byte[]{0x00}, q);
  264. byte[] qLength = ByteBuffer.allocate(4).putInt(q.length).array();
  265. byte[] g = ((DSAPublicKey) dsa.getPublic()).getParams().getG().toByteArray();
  266. if(g[0] != 0x00) g = HelperUtils.concat(new byte[]{0x00}, g);
  267. byte[] gLength = ByteBuffer.allocate(4).putInt(g.length).array();
  268. byte[] y = ((DSAPublicKey) dsa.getPublic()).getY().toByteArray();
  269. if(y[0] != 0x00) y = HelperUtils.concat(new byte[]{0x00}, y);
  270. byte[] yLength = ByteBuffer.allocate(4).putInt(y.length).array();
  271. K_S = HelperUtils.concat(stringLength, string, pLength, p, qLength, q, gLength, g, yLength, y);
  272. } catch (Exception e) {
  273. e.printStackTrace();
  274. }
  275. }
  276. /**
  277. * Generates the SHA-1 Hash from several values
  278. */
  279. private void generateSha1Hash() {
  280. try {
  281. MessageDigest sha = MessageDigest.getInstance("SHA-1");
  282. sha.update(V_C);
  283. sha.update(V_S);
  284. sha.update(I_C);
  285. sha.update(I_S);
  286. sha.update(K_S);
  287. sha.update(e);
  288. sha.update(f);
  289. sha.update(k);
  290. h = sha.digest();
  291. } catch (Exception e) {
  292. e.printStackTrace();
  293. }
  294. }
  295. /**
  296. * Generates the signature of the hash using DSA algorithm with SHA-1
  297. */
  298. private void generateSignature() {
  299. //FIXME something is wrong with this signature.. maybe one of the used components is generated wrong?!
  300. try {
  301. Signature sig = Signature.getInstance("SHA1withDSA");
  302. sig.initVerify(dsa.getPublic());
  303. sig.initSign(dsa.getPrivate());
  304. sig.update(h);
  305. this.sig = extractSignature(sig.sign());
  306. } catch (Exception e) {
  307. e.printStackTrace();
  308. }
  309. }
  310. /**
  311. * Extracts the type of the client
  312. * @param request containing the clients type
  313. */
  314. private void extractType(byte[] request) {
  315. int length = 0;
  316. for(int i = 8; i < request.length; i++, length++) { //start at 8 because "SSH-2.0-" is not part of type
  317. if(request[i] == 0x0d) break; //find the end of the type: '\r'
  318. }
  319. V_C = new byte[length];
  320. System.arraycopy(request, 8, V_C, 0, length);
  321. }
  322. /**
  323. * Extracts the cookie from the Kex Init client request
  324. * @param request containing the clients cookie
  325. */
  326. private void extractCookie(byte[] request) {
  327. int pos = 0;
  328. if(request[5] != 0x14) { //if type packet is in front of kex init
  329. pos = 1; //start behind the end of type message
  330. for(int i = 0; i < request.length; i++, pos++) {
  331. if(request[i] == 0x0a) break; //find end of type message: '\n'
  332. }
  333. }
  334. I_C = new byte[16];
  335. System.arraycopy(request, 6+pos, I_C, 0, 16); //srcLen: headersize+position after type packet
  336. }
  337. /**
  338. * Extracts the public key from the DH Kex Request
  339. * @param request containing the clients public key
  340. */
  341. private void extractPubKey(byte[] request) {
  342. e = new byte[byteToInt(new byte[] {request[6], request[7], request[8], request[9]})];
  343. for(int i = 0; i < e.length; i++) {
  344. e[i] = request[i+10];
  345. }
  346. }
  347. /**
  348. * Converts a byte[] to int
  349. * @param bytes that are converted
  350. * @return converted byte[] as int
  351. */
  352. private static int byteToInt(byte[] bytes) {
  353. int ret = 0;
  354. for (int i=0; i < bytes.length; i++) {
  355. ret <<= 8;
  356. ret |= bytes[i] & 0xFF;
  357. }
  358. return ret;
  359. }
  360. /**
  361. * Generates a random byte[] of a specified size
  362. * @param size of the byte[]
  363. * @return random byte[]
  364. */
  365. private byte[] randomBytes(int size) {
  366. byte[] bytes = new byte[size];
  367. Random rdm = new Random();
  368. rdm.nextBytes(bytes);
  369. return bytes;
  370. }
  371. /**
  372. * Extracts r and s from a DSA-signature
  373. * @param signature
  374. * @return r and s as byte[]
  375. */
  376. private byte[] extractSignature(byte[] signature) {
  377. //{ r INTEGER, s INTEGER }
  378. int length = 0;
  379. int index = 3;
  380. length = signature[index++] & 0xff;
  381. byte[] r = new byte[length];
  382. System.arraycopy(signature, index, r, 0, r.length);
  383. index = index + length + 1;
  384. length = signature[index++] & 0xff;
  385. byte[] s = new byte[length];
  386. System.arraycopy(signature, index, s, 0, s.length);
  387. byte[] result = new byte[40];
  388. // result must be 40 bytes, but length of r and s may not be 20 bytes
  389. System.arraycopy(r,
  390. (r.length > 20) ? 1 : 0,
  391. result,
  392. (r.length > 20) ? 0 : 20 - r.length,
  393. (r.length > 20) ? 20 : r.length);
  394. System.arraycopy(s,
  395. (s.length > 20) ? 1 : 0,
  396. result,
  397. (s.length > 20) ? 20 : 40 - s.length,
  398. (s.length > 20) ? 20 : s.length);
  399. return result;
  400. }
  401. }