token-validator: generate authorizedkeys file

This commit is contained in:
nemunaire 2018-02-23 20:43:51 +01:00 committed by Pierre-Olivier Mercier
parent 36db72ba07
commit 2ee32cb45b
2 changed files with 42 additions and 1 deletions

View File

@ -59,6 +59,7 @@ func main() {
var baseURL = flag.String("baseurl", "/", "URL prepended to each URL")
flag.StringVar(&StaticDir, "static", "./htdocs/", "Directory containing static files")
flag.StringVar(&sharedSecret, "sharedsecret", "adelina", "secret used to communicate with remote validator")
flag.StringVar(&AuthorizedKeyLocation, "authorizedkeyslocation", Authorizedkeyslocation, "File for allowing user to SSH to the machine")
flag.Parse()
// Sanitize options

View File

@ -5,19 +5,27 @@ import (
"encoding/json"
"encoding/hex"
"errors"
"net/http"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/julienschmidt/httprouter"
)
var AuthorizedKeyLocation = "/var/lib/adlin/.ssh/authorized_keys"
func init() {
router.GET("/sshkeys/", apiHandler(
func(httprouter.Params, []byte) (interface{}, error) {
return getStudentKeys()
}))
router.POST("/sshkeys/", rawHandler(receiveKey))
router.GET("/sshkeys/authorizedkey", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
dumpAuthorizedKeysFile(w)
})
}
type StudentKey struct {
@ -63,6 +71,10 @@ func (s Student) NewKey(key string) (k StudentKey, err error) {
}
}
func (k StudentKey) GetStudent() (Student, error) {
return getStudent(int(k.IdStudent))
}
func (k StudentKey) Update() (int64, error) {
if res, err := DBExec("UPDATE student_keys SET id_student = ?, sshkey = ?, time = ? WHERE id_key = ?", k.IdStudent, k.Key, k.Time, k.Id); err != nil {
return 0, err
@ -117,6 +129,34 @@ func receiveKey(r *http.Request, ps httprouter.Params, body []byte) (interface{}
}
log.Printf("%s just pushed sshkey\n", std.Login)
if len(AuthorizedKeyLocation) > 0 {
file, err := os.Create(AuthorizedKeyLocation)
if err != nil {
log.Fatal("Cannot create file", err)
}
defer file.Close()
dumpAuthorizedKeysFile(file)
}
return "Key imported", nil
}
}
func dumpAuthorizedKeysFile(w io.Writer) {
seen := map[string]interface{}{}
if keys, _ := getStudentKeys(); keys != nil {
for _, k := range keys {
if _, exists := seen[k.Key]; exists {
continue
} else {
seen[k.Key] = true
}
s, _ := k.GetStudent()
w.Write([]byte("command=\"/adlin.sh " + fmt.Sprintf("%d", k.IdStudent) + " '" + s.Login + "'\",no-pty,no-agent-forwarding,no-port-forwarding ssh-ed25519 " + k.Key + fmt.Sprintf(" Student#%d-%q\n", k.IdStudent, s.Login)))
}
}
}