harshraj21 commited on
Commit
c7ff161
·
0 Parent(s):

Initial CyberLog-GPT deployment

Browse files
Files changed (6) hide show
  1. Dockerfile +10 -0
  2. README.md +11 -0
  3. app.py +170 -0
  4. landing.html +0 -0
  5. requirements.txt +3 -0
  6. ui.html +0 -0
Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+ WORKDIR /app
3
+ COPY requirements.txt .
4
+ RUN pip install --no-cache-dir -r requirements.txt
5
+ COPY app.py .
6
+ COPY ui.html .
7
+ COPY landing.html .
8
+ COPY cyberlog_gpt.pt .
9
+ EXPOSE 7860
10
+ CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--timeout", "180", "app:app"]
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CyberLog-GPT
3
+ emoji: 🔐
4
+ colorFrom: green
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+ # 🔐 CyberLog-GPT
10
+ AI-powered cybersecurity log generator. GPT transformer trained from scratch in PyTorch.
11
+ Generates realistic syslog, firewall, SIEM, and attack logs. Max 500 lines per request.
app.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, time, json, random
2
+ from datetime import datetime
3
+ import torch, torch.nn as nn, torch.nn.functional as F
4
+ from flask import Flask, request, jsonify, render_template_string
5
+
6
+ app = Flask(__name__)
7
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
+ MAX_LINES = 500
9
+ MODEL, ENCODE, DECODE, CKPT, BLOCK_SIZE = None, None, None, None, 256
10
+
11
+ ATTACK_PROMPTS = {
12
+ "random":"","ssh":"2024-01-15 03:22:11 auth-server sshd",
13
+ "portscan":"2024-01-15 02:11:04 SNORT[3]: [1:1000001:1] PORT SCAN",
14
+ "firewall":"2024-01-15 14:33:07 FW01 kernel: [BLOCK] IN=eth0",
15
+ "webattack":"2024-01-15 11:44:22 web01 apache2:",
16
+ "malware":"THREAT_INTEL: C2_BEACON_DETECTED",
17
+ "privesc":"2024-01-15 04:12:09 db01 sudo:",
18
+ "exfil":"DLP_ALERT: [CRITICAL] Large data transfer",
19
+ "ransomware":"SIEM_ALERT: [CRITICAL] RANSOMWARE",
20
+ "exploit":"IDS_ALERT: [HIGH] Exploit attempt detected",
21
+ "siem":"SIEM_ALERT: [HIGH]",
22
+ }
23
+ RANDOM_POOL = [("ssh",.15),("portscan",.12),("firewall",.18),("webattack",.15),
24
+ ("malware",.10),("privesc",.07),("exfil",.06),("ransomware",.05),
25
+ ("exploit",.08),("siem",.04)]
26
+
27
+ def get_random_prompt():
28
+ types,weights = zip(*RANDOM_POOL)
29
+ t = random.choices(types, weights=weights, k=1)[0]
30
+ return ATTACK_PROMPTS[t], t
31
+
32
+ def build_model(vocab_size, n_embd, n_head, n_layer, block_size):
33
+ class Head(nn.Module):
34
+ def __init__(self,hs):
35
+ super().__init__()
36
+ self.q=nn.Linear(n_embd,hs,bias=False)
37
+ self.k=nn.Linear(n_embd,hs,bias=False)
38
+ self.v=nn.Linear(n_embd,hs,bias=False)
39
+ self.register_buffer("tril",torch.tril(torch.ones(block_size,block_size)))
40
+ self.drop=nn.Dropout(0)
41
+ def forward(self,x):
42
+ B,T,C=x.shape
43
+ q,k,v=self.q(x),self.k(x),self.v(x)
44
+ w=q@k.transpose(-2,-1)*(k.shape[-1]**-.5)
45
+ w=w.masked_fill(self.tril[:T,:T]==0,float("-inf"))
46
+ return self.drop(F.softmax(w,dim=-1))@v
47
+ class MHA(nn.Module):
48
+ def __init__(self,nh,hs):
49
+ super().__init__()
50
+ self.heads=nn.ModuleList([Head(hs) for _ in range(nh)])
51
+ self.proj=nn.Linear(hs*nh,n_embd)
52
+ self.drop=nn.Dropout(0)
53
+ def forward(self,x): return self.drop(self.proj(torch.cat([h(x) for h in self.heads],dim=-1)))
54
+ class FF(nn.Module):
55
+ def __init__(self,n):
56
+ super().__init__()
57
+ self.net=nn.Sequential(nn.Linear(n,4*n),nn.GELU(),nn.Linear(4*n,n),nn.Dropout(0))
58
+ def forward(self,x): return self.net(x)
59
+ class Block(nn.Module):
60
+ def __init__(self):
61
+ super().__init__()
62
+ hs=n_embd//n_head
63
+ self.sa=MHA(n_head,hs);self.ff=FF(n_embd)
64
+ self.ln1=nn.LayerNorm(n_embd);self.ln2=nn.LayerNorm(n_embd)
65
+ def forward(self,x):
66
+ x=x+self.sa(self.ln1(x)); return x+self.ff(self.ln2(x))
67
+ class GPT(nn.Module):
68
+ def __init__(self):
69
+ super().__init__()
70
+ self.te=nn.Embedding(vocab_size,n_embd)
71
+ self.pe=nn.Embedding(block_size,n_embd)
72
+ self.blocks=nn.Sequential(*[Block() for _ in range(n_layer)])
73
+ self.ln=nn.LayerNorm(n_embd)
74
+ self.head=nn.Linear(n_embd,vocab_size)
75
+ def forward(self,idx,targets=None):
76
+ B,T=idx.shape
77
+ x=self.te(idx)+self.pe(torch.arange(T,device=DEVICE))
78
+ logits=self.head(self.ln(self.blocks(x)))
79
+ if targets is None: return logits,None
80
+ B,T,C=logits.shape
81
+ return logits,F.cross_entropy(logits.view(B*T,C),targets.view(B*T))
82
+ @torch.no_grad()
83
+ def generate(self,idx,n,temperature=1.0,top_k=None):
84
+ for _ in range(n):
85
+ ic=idx[:,-block_size:]
86
+ logits,_=self(ic)
87
+ logits=logits[:,-1,:]/temperature
88
+ if top_k:
89
+ v,_=torch.topk(logits,min(top_k,logits.size(-1)))
90
+ logits[logits<v[:,[-1]]]=float("-inf")
91
+ idx=torch.cat((idx,torch.multinomial(F.softmax(logits,-1),1)),dim=1)
92
+ return idx
93
+ return GPT()
94
+
95
+ def load_model():
96
+ global MODEL,ENCODE,DECODE,CKPT,BLOCK_SIZE
97
+ if not os.path.exists("cyberlog_gpt.pt"): return False
98
+ try:
99
+ ckpt=torch.load("cyberlog_gpt.pt",map_location=DEVICE)
100
+ cfg=ckpt["config"]
101
+ stoi,itos=ckpt["stoi"],ckpt["itos"]
102
+ BLOCK_SIZE=cfg["block_size"]
103
+ ENCODE=lambda s:[stoi[c] for c in s if c in stoi]
104
+ DECODE=lambda l:"".join([itos[i] for i in l])
105
+ m=build_model(ckpt["vocab_size"],cfg["n_embd"],cfg["n_head"],cfg["n_layer"],cfg["block_size"]).to(DEVICE)
106
+ m.load_state_dict(ckpt["model_state_dict"])
107
+ m.eval()
108
+ MODEL,CKPT=m,ckpt
109
+ print(f"Model loaded: {sum(p.numel() for p in m.parameters())/1e6:.2f}M params")
110
+ return True
111
+ except Exception as e:
112
+ print(f"Load error: {e}"); return False
113
+
114
+ load_model()
115
+
116
+ @app.route("/api/generate",methods=["POST"])
117
+ def api_generate():
118
+ if MODEL is None: return jsonify({"error":"Model not loaded"}),503
119
+ d=request.get_json(silent=True) or {}
120
+ attack_type=d.get("attack_type","random")
121
+ n_lines=max(1,min(int(d.get("n_lines",20)),MAX_LINES))
122
+ temperature=max(0.3,min(float(d.get("temperature",0.7)),1.5))
123
+ top_k=max(5,min(int(d.get("top_k",40)),100))
124
+ fmt=d.get("format","log")
125
+ custom_prompt=str(d.get("custom_prompt","")).strip()[:200]
126
+ actual_type=attack_type
127
+ if custom_prompt: prompt=custom_prompt
128
+ elif attack_type=="random": prompt,actual_type=get_random_prompt()
129
+ else: prompt=ATTACK_PROMPTS.get(attack_type,"")
130
+ try:
131
+ t0=time.time()
132
+ ctx=torch.tensor(ENCODE(prompt),dtype=torch.long,device=DEVICE).unsqueeze(0) if prompt else torch.zeros((1,1),dtype=torch.long,device=DEVICE)
133
+ ids=MODEL.generate(ctx,min(n_lines*150,75000),temperature=temperature,top_k=top_k)
134
+ raw=DECODE(ids[0].tolist())
135
+ lines=[l for l in raw.split("\n") if l.strip()][:n_lines]
136
+ elapsed=round((time.time()-t0)*1000)
137
+ if fmt=="json":
138
+ entries=[{"id":i+1,"raw":l,"attack_type":actual_type,"generated_at":datetime.utcnow().isoformat()+"Z"} for i,l in enumerate(lines)]
139
+ output=json.dumps({"logs":entries,"count":len(entries),"model":"CyberLog-GPT"},indent=2)
140
+ elif fmt=="csv":
141
+ rows=["id,timestamp,raw_log,attack_type"]
142
+ for i,l in enumerate(lines):
143
+ ts=l[:19] if len(l)>19 else datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
144
+ rows.append(f\'{i+1},{ts},"{l.replace(",",";").replace(chr(34),chr(92)+chr(34))}",{actual_type}\')
145
+ output="\n".join(rows)
146
+ else: output="\n".join(lines)
147
+ return jsonify({"logs":output,"lines_count":len(lines),"chars_count":len(output),"tokens_used":len(ids[0]),"elapsed_ms":elapsed,"attack_type":actual_type,"format":fmt})
148
+ except Exception as e:
149
+ return jsonify({"error":str(e)}),500
150
+
151
+ @app.route("/api/info")
152
+ def api_info():
153
+ if MODEL is None: return jsonify({"status":"not_loaded"}),503
154
+ total=sum(p.numel() for p in MODEL.parameters())
155
+ return jsonify({"status":"ready","parameters_M":round(total/1e6,2),"train_loss":round(CKPT["final_train_loss"],4),"val_loss":round(CKPT["final_val_loss"],4),"vocab_size":CKPT["vocab_size"],"block_size":BLOCK_SIZE,"device":str(DEVICE),"max_lines":MAX_LINES})
156
+
157
+ @app.route("/api/health")
158
+ def health(): return jsonify({"status":"ok","model_loaded":MODEL is not None})
159
+
160
+ @app.route("/")
161
+ def landing():
162
+ if os.path.exists("landing.html"): return open("landing.html").read()
163
+ return open("ui.html").read() if os.path.exists("ui.html") else "<h1>CyberLog-GPT</h1>"
164
+
165
+ @app.route("/app")
166
+ def index():
167
+ return open("ui.html").read() if os.path.exists("ui.html") else "<h1>App UI missing</h1>"
168
+
169
+ if __name__=="__main__":
170
+ app.run(host="0.0.0.0",port=int(os.environ.get("PORT",7860)),debug=False)
landing.html ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ flask==3.0.0
2
+ torch==2.1.0
3
+ gunicorn==21.2.0
ui.html ADDED
The diff for this file is too large to render. See raw diff