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 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2015-2019 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package daemon
import (
"encoding/json"
"fmt"
"net/http"
"os/user"
"path/filepath"
"regexp"
"time"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/assertstate"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/strutil"
)
var (
loginCmd = &Command{
Path: "/v2/login",
POST: loginUser,
PolkitOK: "io.snapcraft.snapd.login",
}
logoutCmd = &Command{
Path: "/v2/logout",
POST: logoutUser,
PolkitOK: "io.snapcraft.snapd.login",
}
// backwards compat; to-be-deprecated
createUserCmd = &Command{
Path: "/v2/create-user",
POST: postCreateUser,
RootOnly: true,
}
usersCmd = &Command{
Path: "/v2/users",
GET: getUsers,
POST: postUsers,
RootOnly: true,
}
)
var (
osutilAddUser = osutil.AddUser
osutilDelUser = osutil.DelUser
)
// userResponseData contains the data releated to user creation/login/query
type userResponseData struct {
ID int `json:"id,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
SSHKeys []string `json:"ssh-keys,omitempty"`
Macaroon string `json:"macaroon,omitempty"`
Discharges []string `json:"discharges,omitempty"`
}
var isEmailish = regexp.MustCompile(`.@.*\..`).MatchString
func loginUser(c *Command, r *http.Request, user *auth.UserState) Response {
var loginData struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
Otp string `json:"otp"`
}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&loginData); err != nil {
return BadRequest("cannot decode login data from request body: %v", err)
}
if loginData.Email == "" && isEmailish(loginData.Username) {
// for backwards compatibility, if no email is provided assume username is the email
loginData.Email = loginData.Username
loginData.Username = ""
}
if loginData.Email == "" && user != nil && user.Email != "" {
loginData.Email = user.Email
}
// the "username" needs to look a lot like an email address
if !isEmailish(loginData.Email) {
return SyncResponse(&resp{
Type: ResponseTypeError,
Result: &errorResult{
Message: "please use a valid email address.",
Kind: client.ErrorKindInvalidAuthData,
Value: map[string][]string{"email": {"invalid"}},
},
Status: 400,
}, nil)
}
overlord := c.d.overlord
st := overlord.State()
theStore := getStore(c)
macaroon, discharge, err := theStore.LoginUser(loginData.Email, loginData.Password, loginData.Otp)
switch err {
case store.ErrAuthenticationNeeds2fa:
return SyncResponse(&resp{
Type: ResponseTypeError,
Result: &errorResult{
Kind: client.ErrorKindTwoFactorRequired,
Message: err.Error(),
},
Status: 401,
}, nil)
case store.Err2faFailed:
return SyncResponse(&resp{
Type: ResponseTypeError,
Result: &errorResult{
Kind: client.ErrorKindTwoFactorFailed,
Message: err.Error(),
},
Status: 401,
}, nil)
default:
switch err := err.(type) {
case store.InvalidAuthDataError:
return SyncResponse(&resp{
Type: ResponseTypeError,
Result: &errorResult{
Message: err.Error(),
Kind: client.ErrorKindInvalidAuthData,
Value: err,
},
Status: 400,
}, nil)
case store.PasswordPolicyError:
return SyncResponse(&resp{
Type: ResponseTypeError,
Result: &errorResult{
Message: err.Error(),
Kind: client.ErrorKindPasswordPolicy,
Value: err,
},
Status: 401,
}, nil)
}
return Unauthorized(err.Error())
case nil:
// continue
}
st.Lock()
if user != nil {
// local user logged-in, set its store macaroons
user.StoreMacaroon = macaroon
user.StoreDischarges = []string{discharge}
// user's email address authenticated by the store
user.Email = loginData.Email
err = auth.UpdateUser(st, user)
} else {
user, err = auth.NewUser(st, loginData.Username, loginData.Email, macaroon, []string{discharge})
}
st.Unlock()
if err != nil {
return InternalError("cannot persist authentication details: %v", err)
}
result := userResponseData{
ID: user.ID,
Username: user.Username,
Email: user.Email,
Macaroon: user.Macaroon,
Discharges: user.Discharges,
}
return SyncResponse(result, nil)
}
func logoutUser(c *Command, r *http.Request, user *auth.UserState) Response {
state := c.d.overlord.State()
state.Lock()
defer state.Unlock()
if user == nil {
return BadRequest("not logged in")
}
_, err := auth.RemoveUser(state, user.ID)
if err != nil {
return InternalError(err.Error())
}
return SyncResponse(nil, nil)
}
// this might need to become a function, if having user admin becomes a config option
var hasUserAdmin = !release.OnClassic
const noUserAdmin = "system user administration via snapd is not allowed on this system"
func postUsers(c *Command, r *http.Request, user *auth.UserState) Response {
if !hasUserAdmin {
return MethodNotAllowed(noUserAdmin)
}
var postData postUserData
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&postData); err != nil {
return BadRequest("cannot decode user action data from request body: %v", err)
}
if decoder.More() {
return BadRequest("spurious content after user action")
}
switch postData.Action {
case "create":
return createUser(c, postData.postUserCreateData)
case "remove":
return removeUser(c, postData.Username, postData.postUserDeleteData)
case "":
return BadRequest("missing user action")
}
return BadRequest("unsupported user action %q", postData.Action)
}
func removeUser(c *Command, username string, opts postUserDeleteData) Response {
// TODO: allow to remove user entries by email as well
// catch silly errors
if username == "" {
return BadRequest("need a username to remove")
}
// check the user is known to snapd
st := c.d.overlord.State()
st.Lock()
_, err := auth.UserByUsername(st, username)
st.Unlock()
if err == auth.ErrInvalidUser {
return BadRequest("user %q is not known", username)
}
if err != nil {
return InternalError(err.Error())
}
// first remove the system user
if err := osutilDelUser(username, &osutil.DelUserOptions{ExtraUsers: !release.OnClassic}); err != nil {
return InternalError(err.Error())
}
// then the UserState
st.Lock()
u, err := auth.RemoveUserByUsername(st, username)
st.Unlock()
// ErrInvalidUser means "not found" in this case
if err != nil && err != auth.ErrInvalidUser {
return InternalError(err.Error())
}
result := map[string]interface{}{
"removed": []userResponseData{
{ID: u.ID, Username: u.Username, Email: u.Email},
},
}
return SyncResponse(result, nil)
}
func postCreateUser(c *Command, r *http.Request, user *auth.UserState) Response {
if !hasUserAdmin {
return Forbidden(noUserAdmin)
}
var createData postUserCreateData
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&createData); err != nil {
return BadRequest("cannot decode create-user data from request body: %v", err)
}
// this is /v2/create-user, meaning we want the
// backwards-compatible wackiness
createData.singleUserResultCompat = true
return createUser(c, createData)
}
func createUser(c *Command, createData postUserCreateData) Response {
// verify request
st := c.d.overlord.State()
st.Lock()
users, err := auth.Users(st)
st.Unlock()
if err != nil {
return InternalError("cannot get user count: %s", err)
}
if !createData.ForceManaged {
if len(users) > 0 && createData.Automatic {
// no users created but no error with the automatic flag
return SyncResponse([]userResponseData{}, nil)
}
if len(users) > 0 {
return BadRequest("cannot create user: device already managed")
}
if release.OnClassic {
return BadRequest("cannot create user: device is a classic system")
}
}
if createData.Automatic {
// Automatic implies known/sudoers
createData.Known = true
createData.Sudoer = true
}
var model *asserts.Model
var serial *asserts.Serial
createKnown := createData.Known
if createKnown {
var err error
st.Lock()
model, err = c.d.overlord.DeviceManager().Model()
st.Unlock()
if err != nil {
return InternalError("cannot create user: cannot get model assertion: %v", err)
}
st.Lock()
serial, err = c.d.overlord.DeviceManager().Serial()
st.Unlock()
if err != nil && err != state.ErrNoState {
return InternalError("cannot create user: cannot get serial: %v", err)
}
}
// special case: the user requested the creation of all known
// system-users
if createData.Email == "" && createKnown {
return createAllKnownSystemUsers(st, model, serial, &createData)
}
if createData.Email == "" {
return BadRequest("cannot create user: 'email' field is empty")
}
var username string
var opts *osutil.AddUserOptions
if createKnown {
username, opts, err = getUserDetailsFromAssertion(st, model, serial, createData.Email)
} else {
username, opts, err = getUserDetailsFromStore(getStore(c), createData.Email)
}
if err != nil {
return BadRequest("%s", err)
}
// FIXME: duplicated code
opts.Sudoer = createData.Sudoer
opts.ExtraUsers = !release.OnClassic
if err := osutilAddUser(username, opts); err != nil {
return BadRequest("cannot create user %s: %s", username, err)
}
if err := setupLocalUser(c.d.overlord.State(), username, createData.Email); err != nil {
return InternalError("%s", err)
}
result := userResponseData{
Username: username,
SSHKeys: opts.SSHKeys,
}
if createData.singleUserResultCompat {
// return a single userResponseData in this case
return SyncResponse(&result, nil)
} else {
return SyncResponse([]userResponseData{result}, nil)
}
}
func getUserDetailsFromStore(theStore snapstate.StoreService, email string) (string, *osutil.AddUserOptions, error) {
v, err := theStore.UserInfo(email)
if err != nil {
return "", nil, fmt.Errorf("cannot create user %q: %s", email, err)
}
if len(v.SSHKeys) == 0 {
return "", nil, fmt.Errorf("cannot create user for %q: no ssh keys found", email)
}
gecos := fmt.Sprintf("%s,%s", email, v.OpenIDIdentifier)
opts := &osutil.AddUserOptions{
SSHKeys: v.SSHKeys,
Gecos: gecos,
}
return v.Username, opts, nil
}
func createAllKnownSystemUsers(st *state.State, modelAs *asserts.Model, serialAs *asserts.Serial, createData *postUserCreateData) Response {
var createdUsers []userResponseData
headers := map[string]string{
"brand-id": modelAs.BrandID(),
}
st.Lock()
db := assertstate.DB(st)
assertions, err := db.FindMany(asserts.SystemUserType, headers)
st.Unlock()
if err != nil && !asserts.IsNotFound(err) {
return BadRequest("cannot find system-user assertion: %s", err)
}
for _, as := range assertions {
email := as.(*asserts.SystemUser).Email()
// we need to use getUserDetailsFromAssertion as this verifies
// the assertion against the current brand/model/time
username, opts, err := getUserDetailsFromAssertion(st, modelAs, serialAs, email)
if err != nil {
logger.Noticef("ignoring system-user assertion for %q: %s", email, err)
continue
}
// ignore already existing users
if _, err := userLookup(username); err == nil {
continue
}
// FIXME: duplicated code
opts.Sudoer = createData.Sudoer
opts.ExtraUsers = !release.OnClassic
if err := osutilAddUser(username, opts); err != nil {
return InternalError("cannot add user %q: %s", username, err)
}
if err := setupLocalUser(st, username, email); err != nil {
return InternalError("%s", err)
}
createdUsers = append(createdUsers, userResponseData{
Username: username,
SSHKeys: opts.SSHKeys,
})
}
return SyncResponse(createdUsers, nil)
}
func getUserDetailsFromAssertion(st *state.State, modelAs *asserts.Model, serialAs *asserts.Serial, email string) (string, *osutil.AddUserOptions, error) {
errorPrefix := fmt.Sprintf("cannot add system-user %q: ", email)
st.Lock()
db := assertstate.DB(st)
st.Unlock()
brandID := modelAs.BrandID()
series := modelAs.Series()
model := modelAs.Model()
a, err := db.Find(asserts.SystemUserType, map[string]string{
"brand-id": brandID,
"email": email,
})
if err != nil {
return "", nil, fmt.Errorf(errorPrefix+"%v", err)
}
// the asserts package guarantees that this cast will work
su := a.(*asserts.SystemUser)
// cross check that the assertion is valid for the given series/model
// check that the signer of the assertion is one of the accepted ones
sysUserAuths := modelAs.SystemUserAuthority()
if len(sysUserAuths) > 0 && !strutil.ListContains(sysUserAuths, su.AuthorityID()) {
return "", nil, fmt.Errorf(errorPrefix+"%q not in accepted authorities %q", email, su.AuthorityID(), sysUserAuths)
}
if len(su.Series()) > 0 && !strutil.ListContains(su.Series(), series) {
return "", nil, fmt.Errorf(errorPrefix+"%q not in series %q", email, series, su.Series())
}
if len(su.Models()) > 0 && !strutil.ListContains(su.Models(), model) {
return "", nil, fmt.Errorf(errorPrefix+"%q not in models %q", model, su.Models())
}
if len(su.Serials()) > 0 {
if serialAs == nil {
return "", nil, fmt.Errorf(errorPrefix + "bound to serial assertion but device not yet registered")
}
serial := serialAs.Serial()
if !strutil.ListContains(su.Serials(), serial) {
return "", nil, fmt.Errorf(errorPrefix+"%q not in serials %q", serial, su.Serials())
}
}
if !su.ValidAt(time.Now()) {
return "", nil, fmt.Errorf(errorPrefix + "assertion not valid anymore")
}
gecos := fmt.Sprintf("%s,%s", email, su.Name())
opts := &osutil.AddUserOptions{
SSHKeys: su.SSHKeys(),
Gecos: gecos,
Password: su.Password(),
ForcePasswordChange: su.ForcePasswordChange(),
}
return su.Username(), opts, nil
}
type postUserData struct {
Action string `json:"action"`
Username string `json:"username"`
postUserCreateData
postUserDeleteData
}
type postUserCreateData struct {
Email string `json:"email"`
Sudoer bool `json:"sudoer"`
Known bool `json:"known"`
ForceManaged bool `json:"force-managed"`
Automatic bool `json:"automatic"`
// singleUserResultCompat indicates whether to preserve
// backwards compatibility, which results in more clunky
// return values (userResponseData OR [userResponseData] vs now
// uniform [userResponseData]); internal, not from JSON.
singleUserResultCompat bool
}
type postUserDeleteData struct{}
var userLookup = user.Lookup
func setupLocalUser(st *state.State, username, email string) error {
user, err := userLookup(username)
if err != nil {
return fmt.Errorf("cannot lookup user %q: %s", username, err)
}
uid, gid, err := osutil.UidGid(user)
if err != nil {
return err
}
authDataFn := filepath.Join(user.HomeDir, ".snap", "auth.json")
if err := osutil.MkdirAllChown(filepath.Dir(authDataFn), 0700, uid, gid); err != nil {
return err
}
// setup new user, local-only
st.Lock()
authUser, err := auth.NewUser(st, username, email, "", nil)
st.Unlock()
if err != nil {
return fmt.Errorf("cannot persist authentication details: %v", err)
}
// store macaroon auth, user's ID, email and username in auth.json in
// the new users home dir
outStr, err := json.Marshal(struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Macaroon string `json:"macaroon"`
}{
ID: authUser.ID,
Username: authUser.Username,
Email: authUser.Email,
Macaroon: authUser.Macaroon,
})
if err != nil {
return fmt.Errorf("cannot marshal auth data: %s", err)
}
if err := osutil.AtomicWriteFileChown(authDataFn, []byte(outStr), 0600, 0, uid, gid); err != nil {
return fmt.Errorf("cannot write auth file %q: %s", authDataFn, err)
}
return nil
}
func getUsers(c *Command, r *http.Request, user *auth.UserState) Response {
st := c.d.overlord.State()
st.Lock()
users, err := auth.Users(st)
st.Unlock()
if err != nil {
return InternalError("cannot get users: %s", err)
}
resp := make([]userResponseData, len(users))
for i, u := range users {
resp[i] = userResponseData{
Username: u.Username,
Email: u.Email,
ID: u.ID,
}
}
return SyncResponse(resp, nil)
}
|