/
job.go
533 lines (442 loc) · 12.7 KB
/
job.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
package db
import (
"time"
"github.com/google/uuid"
"github.com/lachlan2k/phatcrack/api/internal/roles"
"github.com/lachlan2k/phatcrack/common/pkg/apitypes"
"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes"
"github.com/lib/pq"
"gorm.io/datatypes"
"gorm.io/gorm"
)
const (
JobStatusCreated = "JobStatus-Created"
JobStatusAwaitingStart = "JobStatus-AwaitingStart"
JobStatusStarted = "JobStatus-Started"
JobStatusExited = "JobStatus-Exited"
)
const (
// Clean exit
JobStopReasonFinished = "JobStopReason-Finished"
// User stopped it
JobStopReasonUserStopped = "JobStopReason-UserStopped"
// Never started in the first place
JobStopReasonFailedToStart = "JobStopReason-FailedToStart"
// General failure
JobStopReasonFailed = "JobStopReason-Failed"
// Agent timed out and we lost contact
JobStopReasonTimeout = "JobStopReason-Timeout"
)
type Job struct {
UUIDBaseModel
HashlistVersion uint
Attack Attack
AttackID *uuid.UUID `gorm:"type:uuid"`
HashcatParams datatypes.JSONType[hashcattypes.HashcatParams]
TargetHashes pq.StringArray `gorm:"type:text[]"`
HashType int
RuntimeData JobRuntimeData `gorm:"constraint:OnDelete:CASCADE;"`
AssignedAgent Agent `gorm:"constraint:OnDelete:SET NULL;"`
AssignedAgentID *uuid.UUID `gorm:"type:uuid"`
}
type JobRuntimeData struct {
SimpleBaseModel
JobID uuid.UUID `gorm:"type:uuid"`
// when we ask the job to start
StartRequestTime time.Time
// when it actually starts on the agent
StartedTime time.Time
StoppedTime time.Time
Status string
StopReason string
ErrorString string
CmdLine string // hashcat command
OutputLines pgJSONBArray[JobRuntimeOutputLine]
StatusUpdates pgJSONBArray[hashcattypes.HashcatStatus]
CrackedHashes pgJSONBArray[JobCrackedHash]
}
const (
JobStdLineStreamStdout = "stdout"
JobStdLineStreamStderr = "stderr"
)
type JobRuntimeOutputLine struct {
Stream string
Line string
}
func (j Job) ToDTO() apitypes.JobDTO {
dto := apitypes.JobDTO{
ID: j.ID.String(),
HashlistVersion: j.HashlistVersion,
AttackID: j.AttackID.String(),
HashcatParams: j.HashcatParams.Data(),
TargetHashes: j.TargetHashes,
HashType: j.HashType,
RuntimeData: j.RuntimeData.ToDTO(),
RuntimeSummary: j.RuntimeData.ToSummaryDTO(),
}
if j.AssignedAgentID == nil {
dto.AssignedAgentID = ""
} else {
dto.AssignedAgentID = j.AssignedAgentID.String()
}
return dto
}
func (r JobRuntimeData) ToDTO() apitypes.JobRuntimeDataDTO {
outlines := make([]apitypes.JobRuntimeOutputLineDTO, len(r.OutputLines.Data))
cracked := make([]apitypes.JobCrackedHashDTO, len(r.CrackedHashes.Data))
for i, line := range r.OutputLines.Data {
outlines[i] = apitypes.JobRuntimeOutputLineDTO{
Stream: line.Data().Stream,
Line: line.Data().Line,
}
}
for i, hash := range r.CrackedHashes.Data {
cracked[i] = hash.Data().ToDTO()
}
return apitypes.JobRuntimeDataDTO{
StartRequestTime: r.StartRequestTime,
StartedTime: r.StartedTime,
StoppedTime: r.StoppedTime,
Status: r.Status,
StopReason: r.StopReason,
ErrorString: r.ErrorString,
OutputLines: outlines,
StatusUpdates: r.StatusUpdates.Unwrap(),
CrackedHashes: cracked,
CmdLine: r.CmdLine,
}
}
func (r *JobRuntimeData) ToSummaryDTO() apitypes.JobRuntimeSummaryDTO {
dto := apitypes.JobRuntimeSummaryDTO{
StartedTime: r.StartedTime.Unix(),
StoppedTime: r.StoppedTime.Unix(),
CmdLine: r.CmdLine,
Hashrate: 0,
PercentComplete: -1,
EstimatedTimeRemaining: -1,
}
statusUpdates := r.StatusUpdates.Unwrap()
if len(statusUpdates) > 0 {
status := statusUpdates[len(statusUpdates)-1]
for _, dev := range status.Devices {
dto.Hashrate += dev.Speed
}
if r.Status == JobStatusStarted {
if status.EstimatedStop > time.Now().Unix() {
dto.EstimatedTimeRemaining = status.EstimatedStop - time.Now().Unix()
}
// This is a tuple with (keyspace covered, total keyspace)
if len(status.Progress) == 2 {
dto.PercentComplete = float32(status.Progress[0]) / float32(status.Progress[1])
}
}
if r.Status == JobStatusExited && r.StopReason == JobStopReasonFinished {
dto.PercentComplete = 100.0
dto.EstimatedTimeRemaining = 0
}
}
return dto
}
func (j *Job) ToSimpleDTO() apitypes.JobSimpleDTO {
return apitypes.JobSimpleDTO{
ID: j.ID.String(),
HashlistVersion: j.HashlistVersion,
AttackID: j.AttackID.String(),
HashType: j.HashType,
AssignedAgentID: j.AssignedAgentID.String(),
}
}
type JobCrackedHash struct {
Hash string
PlaintextHex string
}
func (h JobCrackedHash) ToDTO() apitypes.JobCrackedHashDTO {
return apitypes.JobCrackedHashDTO{
Hash: h.Hash,
PlaintextHex: h.PlaintextHex,
}
}
func GetJob(jobId string, includeRuntimeData bool) (*Job, error) {
var job Job
inst := GetInstance()
if includeRuntimeData {
inst = inst.Preload("RuntimeData")
}
err := inst.First(&job, "id = ?", jobId).Error
if err != nil {
return nil, err
}
return &job, nil
}
func GetAllPendingJobs(includeRuntimeData bool) ([]Job, error) {
jobs := []Job{}
inst := GetInstance()
if includeRuntimeData {
inst = inst.Preload("RuntimeData")
}
err := inst.
Joins("join job_runtime_data on job_runtime_data.job_id = jobs.id").
Where("job_runtime_data.status = ?", JobStatusAwaitingStart).
Find(&jobs).Error
if err != nil {
return nil, err
}
return jobs, err
}
func GetAllIncompleteJobs(includeRuntimeData bool) ([]Job, error) {
jobs := []Job{}
inst := GetInstance()
if includeRuntimeData {
inst = inst.Preload("RuntimeData")
}
err := inst.
Joins("join job_runtime_data on job_runtime_data.job_id = jobs.id").
Where("job_runtime_data.status != ?", JobStatusExited).
Find(&jobs).Error
if err != nil {
return nil, err
}
return jobs, err
}
type RunningJobForUser struct {
ProjectID uuid.UUID
HashlistID uuid.UUID
AttackID uuid.UUID
JobID uuid.UUID
}
func (j *RunningJobForUser) ToDTO() apitypes.RunningJobForUserDTO {
return apitypes.RunningJobForUserDTO{
ProjectID: j.ProjectID.String(),
HashlistID: j.HashlistID.String(),
AttackID: j.AttackID.String(),
JobID: j.JobID.String(),
}
}
type RunningJobsForUser []RunningJobForUser
func (jobs RunningJobsForUser) ToDTO() []apitypes.RunningJobForUserDTO {
out := make([]apitypes.RunningJobForUserDTO, len(jobs))
for i, job := range jobs {
out[i] = job.ToDTO()
}
return out
}
func GetAllRunningJobsForUser(user *User) (RunningJobsForUser, error) {
jobs := []RunningJobForUser{}
query := GetInstance().
Table("job_runtime_data").
Select("projects.id as project_id, hashlists.id as hashlist_id, attacks.id as attack_id, jobs.id as job_id").
Joins("join jobs on jobs.id = job_runtime_data.job_id").
Joins("join attacks on attacks.id = jobs.attack_id").
Joins("join hashlists on hashlists.id = attacks.hashlist_id").
Joins("join projects on projects.id = hashlists.project_id")
if user.HasRole(roles.RoleAdmin) {
query = query.Where("job_runtime_data.status = ?", JobStatusStarted)
} else {
query = query.
Joins("left join project_shares on project_shares.project_id = projects.id").
Where("job_runtime_data.status = ? and (owner_user_id = ? or project_shares.user_id = ?)", JobStatusStarted, user.ID, user.ID)
}
err := query.Find(&jobs).Error
if err != nil {
return nil, err
}
return jobs, err
}
func GetJobProjID(jobId string) (string, error) {
var result struct {
ProjectID uuid.UUID
}
err := GetInstance().Table("jobs").
Select("hashlists.project_id as project_id").
Joins("join attacks on attacks.id = jobs.attack_id").
Joins("join hashlists on hashlists.id = attacks.hashlist_id").
Where("jobs.id = ?", jobId).
Scan(&result).Error
if err != nil {
return "", err
}
return result.ProjectID.String(), nil
}
func CreateJob(job *Job) (*Job, error) {
if job.RuntimeData.Status == "" {
job.RuntimeData.Status = JobStatusCreated
job.RuntimeData.OutputLines.Init()
job.RuntimeData.StatusUpdates.Init()
job.RuntimeData.CrackedHashes.Init()
}
return job, GetInstance().Create(job).Error
}
func GetJobsForHashlist(hashlistId string) ([]Job, error) {
result := []Job{}
err := GetInstance().
Joins("join attacks on attacks.id = jobs.attack_id").
Where("attacks.hashlist_id = ?", hashlistId).
Find(&result).Error
if err != nil {
return nil, err
}
return result, nil
}
func GetJobsForProject(projectId string) ([]Job, error) {
result := []Job{}
err := GetInstance().
Joins("join attacks on attacks.id = jobs.attack_id").
Joins("join hashlists on hashlists.id = attacks.hashlist_id").
Where("hashlists.project_id = ?", projectId).
Find(&result).Error
if err != nil {
return nil, err
}
return result, nil
}
func CreateJobTx(job *Job, tx *gorm.DB) (*Job, error) {
if job.RuntimeData.Status == "" {
job.RuntimeData.Status = JobStatusCreated
job.RuntimeData.OutputLines.Init()
job.RuntimeData.StatusUpdates.Init()
job.RuntimeData.CrackedHashes.Init()
}
return job, tx.Create(job).Error
}
func SetJobStarted(jobId string, cmdLine string, startTime time.Time) error {
jobUuid, err := uuid.Parse(jobId)
if err != nil {
return err
}
return GetInstance().
Where("job_id = ?", jobUuid).
Updates(&JobRuntimeData{
JobID: jobUuid,
CmdLine: cmdLine,
Status: JobStatusStarted,
StartedTime: startTime,
}).Error
}
func SetJobExited(jobId string, reason string, errStr string, exitTime time.Time) error {
jobUuid, err := uuid.Parse(jobId)
if err != nil {
return err
}
return GetInstance().Transaction(func(tx *gorm.DB) error {
var current struct {
ErrorString string
}
err := tx.
Table("job_runtime_data").
Where("job_id = ?", jobId).
Find(¤t).
Error
if err != nil {
return err
}
newErrStr := current.ErrorString
if newErrStr != "" {
newErrStr += "\n"
}
newErrStr += errStr
return tx.Where("job_id = ?", jobUuid).
Updates(&JobRuntimeData{
JobID: jobUuid,
Status: JobStatusExited,
StopReason: reason,
StoppedTime: exitTime,
ErrorString: newErrStr,
}).Error
})
}
func SetJobScheduled(jobId string, agentId string) error {
jobUuid, err := uuid.Parse(jobId)
if err != nil {
return err
}
agentUuid, err := uuid.Parse(agentId)
if err != nil {
return err
}
return GetInstance().Transaction(func(tx *gorm.DB) error {
err := tx.
Where("job_id = ?", jobUuid).
Updates(&JobRuntimeData{
JobID: jobUuid,
Status: JobStatusAwaitingStart,
StartRequestTime: time.Now(),
}).Error
if err != nil {
return err
}
return tx.
Where("id = ?", jobUuid).
Updates(&Job{
AssignedAgentID: &agentUuid,
}).Error
})
}
func AddJobCrackedHash(jobId string, hash string, plaintextHex string) error {
dbLine := datatypes.NewJSONType(JobCrackedHash{
Hash: hash,
PlaintextHex: plaintextHex,
})
err := GetInstance().Exec(
"update job_runtime_data set cracked_hashes = array_append(cracked_hashes, ?) where job_id = ?",
dbLine, jobId,
).Error
if err != nil {
return err
}
return GetInstance().
Table("hashlist_hashes").
Where("normalized_hash = ?", hash).
Updates(&HashlistHash{
PlaintextHex: plaintextHex,
IsCracked: true,
}).Error
}
// TODO: actually, on second thought, I want to keep all stderr lines, and only roll-over stdout lines
const MaxJobOutputs = 10
func AddJobStdline(jobId string, stream string, line string) error {
dbLine := datatypes.NewJSONType(JobRuntimeOutputLine{
Stream: stream,
Line: line,
})
return GetInstance().Exec(
"update job_runtime_data set output_lines = array_append(output_lines[array_upper(output_lines, 1) - ?:], ?) where job_id = ?",
MaxJobOutputs-2, dbLine, jobId,
).Error
}
func AddJobStatusUpdate(jobId string, status hashcattypes.HashcatStatus) error {
return GetInstance().Exec(
"update job_runtime_data set status_updates = array_append(status_updates[array_upper(status_updates, 1) - ?:], ?) where job_id = ?",
MaxJobOutputs-2, datatypes.NewJSONType(status), jobId,
).Error
}
func GetJobHashtype(jobId string) (uint, error) {
var result struct {
HashType uint
}
err := GetInstance().
Table("jobs").
Select("hashlists.hash_type as hash_type").
Joins("join attacks on attacks.id = jobs.attack_id").
Joins("join hashlists on attacks.hashlist_id = hashlists.id").
Where("jobs.id = ?", jobId).
Scan(&result).Error
if err != nil {
return 0, err
}
return result.HashType, nil
}
func GetJobsForAttack(attackId string, includeRuntimeData bool) ([]Job, error) {
jobs := []Job{}
inst := GetInstance()
if includeRuntimeData {
inst = inst.Preload("RuntimeData")
}
err := inst.
Select("distinct on (jobs.id) jobs.*").
Where("jobs.attack_id = ?", attackId).
Find(&jobs).Error
if err != nil {
return nil, err
}
return jobs, nil
}