create.go 7.24 KB
Newer Older
Loïck Bonniot's avatar
Loïck Bonniot committed
1 2 3 4 5 6 7 8
package user

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"errors"
	"fmt"
9
	"log"
Loïck Bonniot's avatar
Loïck Bonniot committed
10 11 12 13 14
	"time"

	"dfss/auth"
	"dfss/dfssp/api"
	"dfss/dfssp/authority"
15
	"dfss/dfssp/contract"
Loïck Bonniot's avatar
Loïck Bonniot committed
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
	"dfss/dfssp/entities"
	"dfss/dfssp/templates"
	"dfss/mgdb"

	"gopkg.in/mgo.v2/bson"
)

// Check if the registration request has usable fields
func checkRegisterRequest(in *api.RegisterRequest) *api.ErrorCode {
	if len(in.Email) == 0 {
		return &api.ErrorCode{Code: api.ErrorCode_INVARG, Message: "Invalid email length"}
	}

	if len(in.Request) == 0 {
		return &api.ErrorCode{Code: api.ErrorCode_INVARG, Message: "Invalid request length"}
	}

	_, err := auth.PEMToCertificateRequest([]byte(in.Request))

	if err != nil {
		return &api.ErrorCode{Code: api.ErrorCode_INVARG, Message: err.Error()}
	}

	return nil
}

// Send the verification email in response to the specified registration request
//
// This method should only be called AFTER checking the RegisterRequest for validity
45
func sendVerificationMail(in *api.RegisterRequest, token string) {
Loïck Bonniot's avatar
Loïck Bonniot committed
46 47
	conn := templates.MailConn()
	if conn == nil {
48 49
		log.Println("Couldn't connect to the dfssp mail server")
		return
Loïck Bonniot's avatar
Loïck Bonniot committed
50 51 52 53 54 55 56 57
	}
	defer func() { _ = conn.Close() }()

	rcpts := []string{in.Email}

	mail := templates.VerificationMail{Token: token}
	content, err := templates.Get("verificationMail", mail)
	if err != nil {
58 59
		log.Println(err)
		return
Loïck Bonniot's avatar
Loïck Bonniot committed
60 61 62 63 64 65 66 67 68 69 70
	}

	err = conn.Send(
		rcpts,
		"[DFSS] Registration email validation",
		content,
		nil,
		nil,
		nil,
	)
	if err != nil {
71 72
		log.Println(err)
		return
Loïck Bonniot's avatar
Loïck Bonniot committed
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
	}
}

// Register checks if the registration request is valid, and if so,
// creates the user entry in the database
//
// If there is already an entry in the database with the same email,
// evaluates the request as invalid
//
// The user's ConnectionInfo field is NOT handled here
// This data should be gathered upon beginning the signing sequence
func Register(manager *mgdb.MongoManager, in *api.RegisterRequest) (*api.ErrorCode, error) {
	// Check the request validity
	errCode := checkRegisterRequest(in)
	if errCode != nil {
		return errCode, nil
	}

	// Generating the random token
	b := make([]byte, 8)
	_, err := rand.Read(b)
	if err != nil {
		return &api.ErrorCode{Code: api.ErrorCode_INTERR, Message: "Error during the generation of the token"}, nil
	}
	token := fmt.Sprintf("%x", b)

	// If there is already an entry with the same mail, do nothing
	var res []entities.User
	err = manager.Get("users").FindAll(bson.M{
		"email": bson.M{"$eq": in.Email},
	}, &res)
	if len(res) != 0 {
		return &api.ErrorCode{Code: api.ErrorCode_INVARG, Message: "An entry already exists with the same mail"}, nil
	}

	// Creating the new user
	user := entities.NewUser()
	user.Email = in.Email
	user.RegToken = token
	user.Csr = in.Request

	// Adding the new user in the database
	ok, err := manager.Get("users").Insert(*user)
	if !ok {
		return &api.ErrorCode{Code: api.ErrorCode_INTERR, Message: "Error during the insertion of the new user"}, err
	}

	// Sending the email
121
	sendVerificationMail(in, token)
Loïck Bonniot's avatar
Loïck Bonniot committed
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

	return &api.ErrorCode{Code: api.ErrorCode_SUCCESS, Message: "Registration successful ; email sent"}, nil
}

// Check if the authentication request has usable fields
func checkAuthRequest(in *api.AuthRequest, certDuration int) error {
	if len(in.Email) == 0 {
		return errors.New("Invalid email length")
	}

	if len(in.Token) == 0 {
		return errors.New("Invalid token length")
	}

	if certDuration < 1 {
		return errors.New("Invalid validity duration")
	}

	return nil
}

// Check if the authentication request was made in time
func checkTokenTimeout(user *entities.User) error {
	now := time.Now().UTC()
	bad := now.After(user.Registration.Add(time.Hour * 24))
	if bad {
		return errors.New("Registration request is over 24 hours old")
	}

	return nil
}

// Gerenate the user's certificate and certificate hash according to the specified parameters
//
// This function should only be called AFTER checking the AuthRequest for validity
func generateUserCert(csr string, certDuration int, parent *x509.Certificate, key *rsa.PrivateKey) ([]byte, []byte, error) {
	x509csr, err := auth.PEMToCertificateRequest([]byte(csr))
	if err != nil {
		return nil, nil, err
	}

	cert, err := auth.GetCertificate(certDuration, auth.GenerateUID(), x509csr, parent, key)
	if err != nil {
		return nil, nil, err
	}

168 169
	c, _ := auth.PEMToCertificate(cert)
	certHash := auth.GetCertificateHash(c)
Loïck Bonniot's avatar
Loïck Bonniot committed
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

	return cert, certHash, nil
}

// Auth checks if the authentication request is valid, and if so,
// generate the certificate and certificate hash for the user, and
// updates the user's entry in the database
//
// If there is already an entry in the database with the same email,
// and that this entry already has a certificate and certificate hash,
// evaluates the request as invalid
//
// The user's ConnectionInfo field is NOT handled here
// This data should be gathered upon beginning the signing sequence
func Auth(pid *authority.PlatformID, manager *mgdb.MongoManager, certDuration int, in *api.AuthRequest) (*api.RegisteredUser, error) {
	// Check the request validity
	err := checkAuthRequest(in, certDuration)
	if err != nil {
		return nil, err
	}

	// Find the user in the database
	var user entities.User

	err = manager.Get("users").Collection.Find(bson.M{
		"email": bson.M{"$eq": in.Email},
	}).One(&user)
	if err != nil {
		return nil, err
	}

	// If the user already has a certificate and certificate hash in the database, does nothing
	if user.Certificate != "" || user.CertHash != "" {
		return nil, errors.New("User is already registered")
	}

	// Check if the delta between now and the moment the user was created (ie the moment he sent the register request) is in bound of 24h
	err = checkTokenTimeout(&user)
	if err != nil {
		return nil, err
	}

	// Check if the token is correct
	if in.Token != user.RegToken {
		return nil, errors.New("Token mismatch")
	}

	// Generate the certificates and hash
	cert, certHash, err := generateUserCert(user.Csr, certDuration, pid.RootCA, pid.Pkey)
	if err != nil {
		return nil, err
	}

	user.Certificate = string(cert)
224 225
	user.CertHash = fmt.Sprintf("%x", certHash)
	user.Expiration = time.Now().AddDate(0, 0, certDuration)
Loïck Bonniot's avatar
Loïck Bonniot committed
226 227 228 229 230 231 232

	// Updating the database
	ok, err := manager.Get("users").UpdateByID(user)
	if !ok {
		return nil, err
	}

233 234 235
	// Update missed contracts in background
	go launchMissedContracts(manager, &user)

Loïck Bonniot's avatar
Loïck Bonniot committed
236 237 238
	// Returning the RegisteredUser message
	return &api.RegisteredUser{ClientCert: user.Certificate}, nil
}
239 240 241 242 243 244

func launchMissedContracts(manager *mgdb.MongoManager, user *entities.User) {

	repository := entities.NewContractRepository(manager.Get("contracts"))
	contracts, err := repository.GetWaitingForUser(user.Email)
	if err != nil {
245
		log.Println("Cannot get missed contracts for user", user.Email+":", err)
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	}

	for _, c := range contracts {

		c.Ready = true
		for i := range c.Signers {
			if c.Signers[i].Email == user.Email {
				c.Signers[i].Hash = user.CertHash
				c.Signers[i].UserID = user.ID
			}
			if len(c.Signers[i].Hash) == 0 {
				c.Ready = false
			}
		}

		// Update contract in database
		_, err = repository.Collection.UpdateByID(c)
		if err != nil {
264
			log.Println("Cannot update missed contract", c.ID, "for user", user.Email+":", err)
265 266 267 268 269 270 271 272 273 274 275
		}

		if c.Ready {
			// Send required mails
			builder := contract.NewContractBuilder(manager, nil)
			builder.Contract = &c
			builder.SendNewContractMail()
		}
	}

}