libfic/flag: add validatorRegexp field

This commit is contained in:
nemunaire 2018-11-16 20:46:19 +01:00 committed by Pierre-Olivier Mercier
parent c2558fe0ec
commit ff56ec9fe3
8 changed files with 111 additions and 35 deletions

View File

@ -189,11 +189,12 @@ func deleteExerciceHint(hint fic.EHint, _ []byte) (interface{}, error) {
} }
type uploadedFlag struct { type uploadedFlag struct {
Label string Label string
Help string Help string
ICase bool IgnoreCase bool
Flag string ValidatorRe *string `json:"validator_regexp"`
Hash []byte Flag string
Value []byte
} }
func createExerciceFlag(exercice fic.Exercice, body []byte) (interface{}, error) { func createExerciceFlag(exercice fic.Exercice, body []byte) (interface{}, error) {
@ -206,7 +207,12 @@ func createExerciceFlag(exercice fic.Exercice, body []byte) (interface{}, error)
return nil, errors.New("Flag not filled") return nil, errors.New("Flag not filled")
} }
return exercice.AddRawFlag(uk.Label, uk.Help, uk.ICase, uk.Flag) var vre *string = nil
if uk.ValidatorRe != nil && len(*uk.ValidatorRe) > 0 {
vre = uk.ValidatorRe
}
return exercice.AddRawFlag(uk.Label, uk.Help, uk.IgnoreCase, vre, []byte(uk.Flag))
} }
func showExerciceFlag(flag fic.Flag, _ fic.Exercice, body []byte) (interface{}, error) { func showExerciceFlag(flag fic.Flag, _ fic.Exercice, body []byte) (interface{}, error) {
@ -226,8 +232,14 @@ func updateExerciceFlag(flag fic.Flag, exercice fic.Exercice, body []byte) (inte
} }
flag.Help = uk.Help flag.Help = uk.Help
flag.IgnoreCase = uk.ICase flag.IgnoreCase = uk.IgnoreCase
flag.Checksum = uk.Hash flag.Checksum = uk.Value
if uk.ValidatorRe != nil && len(*uk.ValidatorRe) > 0 {
flag.ValidatorRegexp = uk.ValidatorRe
} else {
flag.ValidatorRegexp = nil
}
if _, err := flag.Update(); err != nil { if _, err := flag.Update(); err != nil {
return nil, err return nil, err

View File

@ -17,6 +17,7 @@ Tous les textes doivent utiliser l'encodage UTF8.
- `[[flag]]` : drapeau classique à valider pour résoudre le challenge : - `[[flag]]` : drapeau classique à valider pour résoudre le challenge :
* `label = "Intitulé"` : (facultatif, par défaut : `Flag`) intitulé du drapeau ; * `label = "Intitulé"` : (facultatif, par défaut : `Flag`) intitulé du drapeau ;
* `raw = 'MieH2athxuPhai6u'` : drapeau exact à trouver ; * `raw = 'MieH2athxuPhai6u'` : drapeau exact à trouver ;
* `validator_regexp = "^(?:sudo +)?(.*)$"` : (facultatif) expression rationnelle dont les groupes capturés serviront comme chaîne à valider (notez que `?:` au début d'un groupe ne le capturera pas) ;
* `ignorecase = true` : (facultatif, par défaut : `false`) ignore la case de ce drapeau ; * `ignorecase = true` : (facultatif, par défaut : `false`) ignore la case de ce drapeau ;
* `help = "Indication"` : (facultatif) chaîne de caractères placée sous le champ du formulaire, idéale pour donner une indication de format ; * `help = "Indication"` : (facultatif) chaîne de caractères placée sous le champ du formulaire, idéale pour donner une indication de format ;
* `[[flag.unlock_file]]` : bloque l'accès à un fichier tant que le flag n'est pas obtenu : * `[[flag.unlock_file]]` : bloque l'accès à un fichier tant que le flag n'est pas obtenu :
@ -29,6 +30,7 @@ Tous les textes doivent utiliser l'encodage UTF8.
- `[[flag_ucq]]` : drapeau sous forme de question à choix unique : - `[[flag_ucq]]` : drapeau sous forme de question à choix unique :
* `label = "Intitulé du groupe"` : (facultatif) intitulé du groupe de choix ; * `label = "Intitulé du groupe"` : (facultatif) intitulé du groupe de choix ;
* `raw = 'MieH2athxuPhai6u'` : drapeau attendu parmi les propositions ; * `raw = 'MieH2athxuPhai6u'` : drapeau attendu parmi les propositions ;
* `validator_regexp = "^(?:sudo +)?(.*)$"` : (facultatif) expression rationnelle dont les groupes capturés serviront comme chaîne à valider (notez que `?:` au début d'un groupe ne le capturera pas) ;
* `help = "Indication"` : (facultatif, uniquement si `displayAs = select`) chaîne de caractères placée sous le champ du formulaire ; * `help = "Indication"` : (facultatif, uniquement si `displayAs = select`) chaîne de caractères placée sous le champ du formulaire ;
* `displayAs = "select|radio"` : (facultatif, par défaut `radio`) manière dont est affichée le choix : `select` pour une liste de choix, `radio` pour des boutons radios ; * `displayAs = "select|radio"` : (facultatif, par défaut `radio`) manière dont est affichée le choix : `select` pour une liste de choix, `radio` pour des boutons radios ;
* `choices_cost = 20` : (facultatif, par défaut `0`) coût pour afficher les choix, avant l'affichage, se comporte comme un `flag` classique (à 0, les choix sont affichés directement) ; * `choices_cost = 20` : (facultatif, par défaut `0`) coût pour afficher les choix, avant l'affichage, se comporte comme un `flag` classique (à 0, les choix sont affichés directement) ;

View File

@ -27,11 +27,12 @@ type ExerciceUnlockFile struct {
// ExerciceFlag holds informations about a "classic" flag. // ExerciceFlag holds informations about a "classic" flag.
type ExerciceFlag struct { type ExerciceFlag struct {
Label string `toml:",omitempty"` Label string `toml:",omitempty"`
Raw string Raw string
IgnoreCase bool `toml:",omitempty"` IgnoreCase bool `toml:",omitempty"`
Help string `toml:",omitempty"` ValidatorRe string `toml:"validator_regexp,omitempty"`
LockedFile []ExerciceUnlockFile `toml:"unlock_file,omitempty"` Help string `toml:",omitempty"`
LockedFile []ExerciceUnlockFile `toml:"unlock_file,omitempty"`
} }
// ExerciceFlagMCQChoice holds a choice for an MCQ flag. // ExerciceFlagMCQChoice holds a choice for an MCQ flag.
@ -57,6 +58,7 @@ type ExerciceFlagUCQ struct {
Label string `toml:",omitempty"` Label string `toml:",omitempty"`
Raw string Raw string
IgnoreCase bool `toml:",omitempty"` IgnoreCase bool `toml:",omitempty"`
ValidatorRe string `toml:"validator_regexp,omitempty"`
Help string `toml:",omitempty"` Help string `toml:",omitempty"`
DisplayAs string `toml:",omitempty"` DisplayAs string `toml:",omitempty"`
Choices_Cost int64 `toml:",omitempty"` Choices_Cost int64 `toml:",omitempty"`

View File

@ -19,6 +19,15 @@ func isFullGraphic(s string) bool {
return true return true
} }
func validatorRegexp(vre string) (validator_regexp *string) {
if len(vre) > 0 {
validator_regexp = &vre
} else {
validator_regexp = nil
}
return
}
// SyncExerciceFlags reads the content of challenge.txt and import "classic" flags as Key for the given challenge. // SyncExerciceFlags reads the content of challenge.txt and import "classic" flags as Key for the given challenge.
func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) { func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
if _, err := exercice.WipeFlags(); err != nil { if _, err := exercice.WipeFlags(); err != nil {
@ -40,7 +49,7 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
errs = append(errs, fmt.Sprintf("%q: WARNING flag #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), nline + 1)) errs = append(errs, fmt.Sprintf("%q: WARNING flag #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), nline + 1))
} }
if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, flag.Raw); err != nil { if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, validatorRegexp(flag.ValidatorRe), []byte(flag.Raw)); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag #%d: %s", path.Base(exercice.Path), nline + 1, err)) errs = append(errs, fmt.Sprintf("%q: error flag #%d: %s", path.Base(exercice.Path), nline + 1, err))
continue continue
} else { } else {
@ -67,7 +76,7 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
errs = append(errs, fmt.Sprintf("%q: WARNING flag UCQ #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), nline + 1)) errs = append(errs, fmt.Sprintf("%q: WARNING flag UCQ #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), nline + 1))
} }
if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, flag.Raw); err != nil { if k, err := exercice.AddRawFlag(flag.Label, flag.Help, flag.IgnoreCase, validatorRegexp(flag.ValidatorRe), []byte(flag.Raw)); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag UCQ #%d: %s", path.Base(exercice.Path), nline + 1, err)) errs = append(errs, fmt.Sprintf("%q: error flag UCQ #%d: %s", path.Base(exercice.Path), nline + 1, err))
continue continue
} else { } else {

View File

@ -162,6 +162,7 @@ CREATE TABLE IF NOT EXISTS exercice_flags(
type VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL,
help VARCHAR(255) NOT NULL, help VARCHAR(255) NOT NULL,
ignorecase BOOLEAN NOT NULL DEFAULT 0, ignorecase BOOLEAN NOT NULL DEFAULT 0,
validator_regexp VARCHAR(255) NULL,
cksum BINARY(64) NOT NULL, cksum BINARY(64) NOT NULL,
FOREIGN KEY(id_exercice) REFERENCES exercices(id_exercice) FOREIGN KEY(id_exercice) REFERENCES exercices(id_exercice)
) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; ) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

View File

@ -296,7 +296,7 @@ func (e Exercice) CheckResponse(respflags map[string]string, respmcq map[int64]b
for _, flag := range flags { for _, flag := range flags {
if res, ok := respflags[flag.Label]; !ok { if res, ok := respflags[flag.Label]; !ok {
valid = false valid = false
} else if !flag.Check(res) { } else if !flag.Check([]byte(res)) {
if !PartialValidation || t.HasPartiallySolved(flag) == nil { if !PartialValidation || t.HasPartiallySolved(flag) == nil {
valid = false valid = false
} }

View File

@ -290,7 +290,7 @@ func (f EFile) GetDepends() ([]Flag, error) {
if err := rows.Scan(&d); err != nil { if err := rows.Scan(&d); err != nil {
return nil, err return nil, err
} }
deps = append(deps, Flag{d, f.IdExercice, "", "", false, []byte{}}) deps = append(deps, Flag{d, f.IdExercice, "", "", false, nil, []byte{}})
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
return nil, err return nil, err

View File

@ -1,30 +1,34 @@
package fic package fic
import ( import (
"bytes"
"errors"
"regexp"
"time" "time"
"golang.org/x/crypto/blake2b" "golang.org/x/crypto/blake2b"
) )
// Flag represents a flag's challenge, stored as hash. // Flag represents a flag's challenge, stored as hash.
type Flag struct { type Flag struct {
Id int64 `json:"id"` Id int64 `json:"id"`
// IdExercice is the identifier of the underlying challenge // IdExercice is the identifier of the underlying challenge
IdExercice int64 `json:"idExercice"` IdExercice int64 `json:"idExercice"`
// Label is the title of the flag as displayed to players // Label is the title of the flag as displayed to players
Label string `json:"label"` Label string `json:"label"`
// Help is a small piece of text that aims to add useful information like flag format, ... // Help is a small piece of text that aims to add useful information like flag format, ...
Help string `json:"help"` Help string `json:"help"`
// IgnoreCase indicates if the case is sensitive to case or not // IgnoreCase indicates if the case is sensitive to case or not
IgnoreCase bool `json:"ignorecase"` IgnoreCase bool `json:"ignorecase"`
// ValidatorRegexp extracts a subset of the player's answer, that will be checked.
ValidatorRegexp *string `json:"validator_regexp"`
// Checksum is the expected hashed flag // Checksum is the expected hashed flag
Checksum []byte `json:"value"` Checksum []byte `json:"value"`
} }
// GetFlags returns a list of flags comming with the challenge. // GetFlags returns a list of flags comming with the challenge.
func (e Exercice) GetFlags() ([]Flag, error) { func (e Exercice) GetFlags() ([]Flag, error) {
if rows, err := DBQuery("SELECT id_flag, id_exercice, type, help, ignorecase, cksum FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil { if rows, err := DBQuery("SELECT id_flag, id_exercice, type, help, ignorecase, validator_regexp, cksum FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil {
return nil, err return nil, err
} else { } else {
defer rows.Close() defer rows.Close()
@ -34,9 +38,10 @@ func (e Exercice) GetFlags() ([]Flag, error) {
var k Flag var k Flag
k.IdExercice = e.Id k.IdExercice = e.Id
if err := rows.Scan(&k.Id, &k.IdExercice, &k.Label, &k.Help, &k.IgnoreCase, &k.Checksum); err != nil { if err := rows.Scan(&k.Id, &k.IdExercice, &k.Label, &k.Help, &k.IgnoreCase, &k.ValidatorRegexp, &k.Checksum); err != nil {
return nil, err return nil, err
} }
flags = append(flags, k) flags = append(flags, k)
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
@ -48,31 +53,59 @@ func (e Exercice) GetFlags() ([]Flag, error) {
} }
// getHashedFlag calculates the expected checksum for the given raw_value. // getHashedFlag calculates the expected checksum for the given raw_value.
func getHashedFlag(raw_value string) [blake2b.Size]byte { func getHashedFlag(raw_value []byte) [blake2b.Size]byte {
hash := blake2b.Sum512([]byte(raw_value)) hash := blake2b.Sum512(raw_value)
return hash return hash
} }
// AddRawFlag creates and fills a new struct Flag, from a non-hashed flag, and registers it into the database. // AddRawFlag creates and fills a new struct Flag, from a non-hashed flag, and registers it into the database.
func (e Exercice) AddRawFlag(name string, help string, ignorecase bool, raw_value string) (Flag, error) { func (e Exercice) AddRawFlag(name string, help string, ignorecase bool, validator_regexp *string, raw_value []byte) (Flag, error) {
if ignorecase {
raw_value = bytes.ToLower(raw_value)
}
// Check that raw value passes through the regexp
if validator_regexp != nil {
if re, err := regexp.Compile(*validator_regexp); err != nil {
return Flag{}, err
} else if res := re.FindSubmatch(raw_value); res == nil {
return Flag{}, errors.New("Expected flag doesn't pass through the validator_regexp")
} else {
raw_value = bytes.Join(res[1:], []byte("+"))
}
}
hash := getHashedFlag(raw_value) hash := getHashedFlag(raw_value)
return e.AddFlag(name, help, ignorecase, hash[:]) return e.AddFlag(name, help, ignorecase, validator_regexp, hash[:])
} }
// AddFlag creates and fills a new struct Flag, from a hashed flag, and registers it into the database. // AddFlag creates and fills a new struct Flag, from a hashed flag, and registers it into the database.
func (e Exercice) AddFlag(name string, help string, ignorecase bool, checksum []byte) (Flag, error) { func (e Exercice) AddFlag(name string, help string, ignorecase bool, validator_regexp *string, checksum []byte) (Flag, error) {
if res, err := DBExec("INSERT INTO exercice_flags (id_exercice, type, help, ignorecase, cksum) VALUES (?, ?, ?, ?, ?)", e.Id, name, help, ignorecase, checksum); err != nil { // Check the regexp compile
if validator_regexp != nil {
if _, err := regexp.Compile(*validator_regexp); err != nil {
return Flag{}, err
}
}
if res, err := DBExec("INSERT INTO exercice_flags (id_exercice, type, help, ignorecase, validator_regexp, cksum) VALUES (?, ?, ?, ?, ?, ?)", e.Id, name, help, ignorecase, validator_regexp, checksum); err != nil {
return Flag{}, err return Flag{}, err
} else if kid, err := res.LastInsertId(); err != nil { } else if kid, err := res.LastInsertId(); err != nil {
return Flag{}, err return Flag{}, err
} else { } else {
return Flag{kid, e.Id, name, help, ignorecase, checksum}, nil return Flag{kid, e.Id, name, help, ignorecase, validator_regexp, checksum}, nil
} }
} }
// Update applies modifications back to the database. // Update applies modifications back to the database.
func (k Flag) Update() (int64, error) { func (k Flag) Update() (int64, error) {
if res, err := DBExec("UPDATE exercice_flags SET id_exercice = ?, type = ?, help = ?, ignorecase = ?, cksum = ? WHERE id_flag = ?", k.IdExercice, k.Label, k.Help, k.IgnoreCase, k.Checksum, k.Id); err != nil { if k.ValidatorRegexp != nil {
if _, err := regexp.Compile(*k.ValidatorRegexp); err != nil {
return 0, err
}
}
if res, err := DBExec("UPDATE exercice_flags SET id_exercice = ?, type = ?, help = ?, ignorecase = ?, validator_regexp = ?, cksum = ? WHERE id_flag = ?", k.IdExercice, k.Label, k.Help, k.IgnoreCase, k.ValidatorRegexp, k.Checksum, k.Id); err != nil {
return 0, err return 0, err
} else if nb, err := res.RowsAffected(); err != nil { } else if nb, err := res.RowsAffected(); err != nil {
return 0, err return 0, err
@ -108,7 +141,24 @@ func (e Exercice) WipeFlags() (int64, error) {
} }
// Check if the given val is the expected one for this flag. // Check if the given val is the expected one for this flag.
func (k Flag) Check(val string) bool { func (k Flag) Check(val []byte) bool {
if k.IgnoreCase {
val = bytes.ToLower(val)
}
// Check that raw value passes through the regexp
if k.ValidatorRegexp != nil {
re := regexp.MustCompile(*k.ValidatorRegexp)
if res := re.FindSubmatch(val); res != nil {
val = bytes.Join(res[1:], []byte("+"))
}
}
// Check that the value is not empty
if len(val) == 0 {
return false
}
hash := getHashedFlag(val) hash := getHashedFlag(val)
if len(k.Checksum) != len(hash) { if len(k.Checksum) != len(hash) {
return false return false