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
// Copyright 2020-2021 Ian Jackson and contributors to Otter
// SPDX-License-Identifier: AGPL-3.0-or-later
// There is NO WARRANTY.

use crate::prelude::*;

visible_slotmap_key!{ Id(b'k') }

static MAGIC_BANNER: &str = 
  "# WARNING - FILE AUTOMATICALLY GENERATED BY OTTER - DO NOT EDIT";

#[derive(Copy,Clone,Serialize,Deserialize)]
#[derive(Eq,PartialEq,Hash,Ord,PartialOrd)]
#[serde(transparent)]
// This will detecte if the slotmap in Accounts gets rewound, without
// updating the authorzed keys.  That might reuse Id values but it
// can't reuse Nonces.
pub struct Nonce([u8; 32]);

// States of a key wrt a particular scope:
//
//                   PerScope       in authorized_keys     leftover key
//                   core    file           a.k._dirty     refcount==0
//                                       if us only        core   file
//
//    ABSENT         -       -         maybe[1] -          -      -
//    GARBAGE        -       -         maybe[1] -          -      y [2]
// **undesriable**   -       -         -                   y      -
//  **illegal**      -       y
//    UNSAVED        y       -         maybe    true       n/a    n/a
//    BROKEN         y       y         maybe    true       n/a    n/a
//    PRESENT        y       y         y        -          n/a    n/a
//
// [1] garbage in the authorised_keys is got rid of next time we
//     write it, so it does not persist indefinitely.
// [2] garbage in Global is deleted when we do the key hashing (which
//     iterates over all keys), which will happen before we add any
//     key.

#[derive(Debug,Clone,Serialize,Deserialize,Default)]
pub struct Global {
  keys: DenseSlotMap<Id, Key>,
  authkeys_dirty: bool,
  #[serde(skip)] fps: Option<FingerprintMap>,
}
type FingerprintMap = HashMap<Arc<Fingerprint>, Id>;

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Key {
  refcount: usize,
  data: PubData,
  nonce: Nonce,
  #[serde(skip)] fp: Option<Result<Arc<Fingerprint>, KeyError>>,
}

#[derive(Debug,Clone,Serialize,Deserialize,Default)]
pub struct PerScope {
  authorised: Vec<Option<ScopeKey>>,
}
#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct ScopeKey {
  id: Id, // owns a refcount
  comment: Comment,
}

#[derive(Debug,Clone,Serialize,Deserialize)]
#[derive(Eq,PartialEq,Hash,Ord,PartialOrd)]
pub struct KeySpec {
  pub id: sshkeys::Id,
  pub nonce: sshkeys::Nonce,
}

#[derive(Error,Copy,Clone,Debug,Hash,Serialize,Deserialize)]
#[error("ssh authorized_keys manipulation failed")]
pub struct AuthKeysManipError { }
impl From<anyhow::Error> for AuthKeysManipError {
  fn from(ae: anyhow::Error) -> AuthKeysManipError {
    error!("authorized_keys manipulation error: {}: {}",
           &config().authorized_keys, ae.d());
    AuthKeysManipError { }
  }
}
impl From<AuthKeysManipError> for MgmtError {
  fn from(akme: AuthKeysManipError) -> MgmtError {
    IE::from(akme).into()
  }
}

mod veneer {
  // openssh_keys's API is a little odd.  We make our own mini-API.
  use crate::prelude::*;
  extern crate openssh_keys;
  use openssh_keys::errors::OpenSSHKeyError;

  // A line in nssh authorized keys firmat.  Might have comment or
  // options.  Might or might not have a newline.  String inside
  // this newtype has not necessarily been syntax checked.
  #[derive(Debug,Clone,Serialize,Deserialize)]
  #[serde(transparent)]
  pub struct AuthkeysLine(pub String);

  // In nssh authorized keys firmat.  No options, no comment.
  #[derive(Debug,Clone,Serialize,Deserialize)]
  #[serde(transparent)]
  pub struct PubData(String);

  #[derive(Debug,Clone,Serialize,Deserialize)]
  #[serde(transparent)]
  pub struct Comment(String /* must not contain newline/cr */);

  // Not Serialize,Deserialize, so we can change the hash, etc.
  #[derive(Debug,Clone,Hash,Eq,PartialEq,Ord,PartialOrd)]
  pub struct Fingerprint(String);

  #[derive(Error,Debug,Clone,Serialize,Deserialize)]
  pub enum KeyError {
    #[error("bad key data: {0}")]                        BadData(String),
    #[error("whitespace in public key data!")]           Whitespace,
    #[error("failed to save key data, possibly broken")] Dirty,
  }

  impl From<OpenSSHKeyError> for KeyError {
    fn from(e: OpenSSHKeyError) -> Self { KeyError::BadData(e.to_string()) }
  }

  impl Display for Comment {
    #[throws(fmt::Error)]
    fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "{}", &self.0)? }
  }
  impl Display for PubData {
    #[throws(fmt::Error)]
    fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "{}", &self.0)? }
  }

  impl AuthkeysLine {
    #[throws(KeyError)]
    pub fn parse(&self) -> (PubData, Comment) {
      let openssh_keys::PublicKey {
        options:_, data, comment
      } = self.0.parse()?;
      let data = openssh_keys::PublicKey {
        data,
        options: None,
        comment: None,
      };
      let data = PubData(data.to_string());
      if data.0.chars().any(|c| c !=' ' && c.is_whitespace()) {
        throw!(KeyError::Whitespace);
      }
      (data, Comment(comment.unwrap_or_default()))
    }
  }

  impl PubData {
    #[throws(KeyError)]
    pub fn fingerprint(&self) -> Fingerprint {
      let k: openssh_keys::PublicKey = self.0.parse()?;
      Fingerprint(k.fingerprint())
    }
  }

  impl Display for Fingerprint {
    #[throws(fmt::Error)]
    fn fmt(&self, f: &mut Formatter) { write!(f, "{}", self.0)? }
  }

}
pub use veneer::*;

format_by_fmt_hex!{Display, for Nonce, .0}
impl Debug for Nonce {
  #[throws(fmt::Error)]
  fn fmt(&self, f: &mut Formatter) {
    write!(f,"Nonce[")?;
    fmt_hex(f, &self.0)?;
    write!(f,"]")?;
  }
}

impl FromStr for KeySpec {
  type Err = anyhow::Error;
  #[throws(anyhow::Error)]
  fn from_str(s: &str) -> KeySpec {
    (||{
      let (id, nonce) = s.split_once(':')
        .ok_or_else(|| anyhow!("missing `:`"))?;
      let id    = id.try_into().context("bad id")?;
      let nonce = nonce.parse().context("bad nonce")?;
      Ok::<_,AE>(KeySpec { id, nonce })
    })().context("failed to parse ssh key spec")?
  }
}

impl FromStr for Nonce {
  type Err = anyhow::Error;
  #[throws(anyhow::Error)]
  fn from_str(s: &str) -> Nonce {
    Nonce(parse_fixed_hex(s).ok_or_else(|| anyhow!("bad nonce syntax"))?)
  }
}

impl PerScope {
  pub fn check(&self, ag: &AccountsGuard, authed_key: &KeySpec,
               auth_in: Authorisation<KeySpec>)
               -> Option<Authorisation<AccountScope>> {
    let gl = &ag.get().ssh_keys;
    for sk in &self.authorised {
      if_chain!{
        if let Some(sk) = sk;
        if sk.id == authed_key.id;
        if let Some(want_key) = gl.keys.get(sk.id);
        if &want_key.nonce == &authed_key.nonce;
        then {
          // We have checked id and nonce, against those allowed
          let auth = auth_in.so_promise();
          return Some(auth);
        }
      }
    }
    None
  }
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct MgmtKeyReport {
  pub key: KeySpec,
  pub data: PubData,
  pub comment: Comment,
  pub problem: Option<KeyError>,
}

impl Display for KeySpec {
  #[throws(fmt::Error)]
  fn fmt(&self, f: &mut fmt::Formatter) {
    write!(f, "{}:{}", self.id, &self.nonce)?;
  }
}

impl Display for MgmtKeyReport {
  #[throws(fmt::Error)]
  fn fmt(&self, f: &mut fmt::Formatter) {
    if let Some(problem) = &self.problem {
      write!(f, "# PROBLEM {} # ", &problem)?;
    }
    write!(f, "{} {} # {}", &self.data, &self.comment, &self.key)?;
  }
}

macro_rules! def_pskeys_get {
  ($trait:ident, $f:ident, $get:ident, $($mut:tt)?) => {
    #[ext(name=$trait)]
    impl DenseSlotMap<AccountId, AccountRecord> {
      #[throws(MgmtError)]
      fn $f(& $($mut)? self, acctid: AccountId) -> & $($mut)? PerScope {
        let record = self.$get(acctid).ok_or(AccountNotFound)?;
        if ! record.account.subaccount.is_empty() {
          throw!(ME::NoSshKeysForSubaccount)
        }
        // We do *not* check that the account is of scope kind Ssh.
        // Installing ssh keys for other scopes is fine.
        // otter(1) will check this.

        & $($mut)? record.ssh_keys
      }
    }
  }
}

def_pskeys_get!{ RecordsExtImm, pskeys_get, get    ,     }
def_pskeys_get!{ RecordsExtMut, pskeys_mut, get_mut, mut }

type Auth = Authorisation<AccountScope>;

impl AccountsGuard {
  #[throws(MgmtError)]
  pub fn sshkeys_report(&self, acctid: AccountId, _:Auth)
                        -> Vec<MgmtKeyReport> {
    let accounts = self.get();
    let gl = &accounts.ssh_keys;
    let ps = &accounts.records.pskeys_get(acctid)?;
    let dirty_error =
      if gl.authkeys_dirty { Some(KeyError::Dirty) }
      else { None };
    ps.authorised.iter().filter_map(|sk| Some({
      let sk = sk.as_ref()?;
      let key = gl.keys.get(sk.id)?;
      let problem = if let Some(Err(ref e)) = key.fp { Some(e) }
                    else { dirty_error.as_ref() };
      MgmtKeyReport {
        key: KeySpec {
        id:      sk.id,
        nonce:   key.nonce.clone(),
        },
        data:    key.data.clone(),
        comment: sk.comment.clone(),
        problem: problem.cloned(),
      }
    }))
      .collect()
  }

  // not a good idea to speicfy a problem, but "whatever"
  #[throws(ME)]
  pub fn sshkeys_add(&mut self, acctid: AccountId,
                     new_akl: AuthkeysLine, _:Auth) -> (usize, Id) {
    let accounts = self.get_mut();
    let gl = &mut accounts.ssh_keys;
    let ps = accounts.records.pskeys_mut(acctid)?;
    let (data, comment) = new_akl.parse()?;
    let fp = data.fingerprint().map_err(KeyError::from)?;
    let fp = Arc::new(fp);
    let _ = gl.fps();
    let fpe = gl.fps.as_mut().unwrap().entry(fp.clone());
    // ABSENT
    let id = {
      let keys = &mut gl.keys;
      *fpe.or_insert_with(||{
        keys.insert(Key {
          data,
          refcount: 0,
          nonce: Nonce(thread_rng().gen()),
          fp: Some(Ok(fp.clone())),
        })
      })
    };
    // **undesirable**
    let key = gl.keys.get_mut(id)
      .ok_or_else(|| internal_error_bydebug(&(id, &fp)))?;
    // GARBAGE
    key.refcount += 1;
    let new_sk = Some(ScopeKey { id, comment });
    let index =
      if let Some((index,_)) = ps.authorised.iter()
          .find_position(|sk| sk.is_none())
      {
        ps.authorised[index] = new_sk;
        index
      } else {
        let index = ps.authorised.len();
        ps.authorised.push(new_sk);
        index
      };
    gl.authkeys_dirty = true;
    // UNSAVED
    self.save_accounts_now()?;
    // BROKEN
    self.get_mut().ssh_keys.rewrite_authorized_keys()?;
    // PRESENT
    (index, id)
  }

  #[throws(ME)]
  pub fn sshkeys_remove(&mut self, acctid: AccountId,
                        index: usize, id: Id, _:Auth) {
    let accounts = self.get_mut();
    let gl = &mut accounts.ssh_keys;
    let ps = accounts.records.pskeys_mut(acctid)?;
    if id == default() {
      throw!(ME::InvalidSshKeyId);
    }
    match ps.authorised.get(index) {
      Some(&Some(ScopeKey{id:tid,..})) if tid == id => { },
      _ => throw!(ME::SshKeyNotFound), /* [ABSEMT..GARBAGE] */
    }
    let key = gl.keys.get_mut(id).ok_or_else(|| internal_logic_error(
      format!("corrupted accounts db: key id {} missing", id)))?;

    // [UNSAVED..PRESENT]
    
    key.refcount -= 1;
    let previously = mem::take(&mut ps.authorised[index]);
    // Now **illegal**, briefly, don't leave it like this!  No-one can
    // observe the illegal state since we have the accounts lock.  If
    // we abort, the in-core version vanishes, leaving a legal state.
    let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(
      || self.save_accounts_now()
    ));

    // Must re-borrow everything since save_accounts_now needed a
    // reference to all of it.
    let accounts = self.get_mut();
    let gl = &mut accounts.ssh_keys;
    let ps = accounts.records.pskeys_mut(acctid).expect("aargh!");
    let key = gl.keys.get_mut(id).expect("aargh!");

    if ! matches!(r, Ok(Ok(()))) {
      key.refcount += 1;
      ps.authorised[index] = previously;
      // [UNSAVED..PRESENT]
      match r {
        Err(payload) => std::panic::resume_unwind(payload),
        Ok(Err(e)) => throw!(e),
        Ok(Ok(())) => panic!(), // handled that earlier
      }
    }
    // [ABSENT..GARBAGE]

    if key.refcount == 0 {
      let key = gl.keys.remove(id).unwrap();
      if let Some(Ok(ref fp)) = key.fp {
        gl.fps().remove(fp);
      }
    }
    // ABSENT
  }

  #[throws(ME)]
  pub fn sshkeys_rewrite_authorized_keys(
    &mut self,
    _:Authorisation<authproofs::Global>
  ) {
    let accounts = self.get_mut();
    let gl = &mut accounts.ssh_keys;
    gl.rewrite_authorized_keys()?;
  }
}

impl Global {
  fn fps(&mut self) -> &mut FingerprintMap {
    let keys = &mut self.keys;
    self.fps.get_or_insert_with(||{

      let mut fps = FingerprintMap::default();
      let mut garbage = vec![];

      for (id, key) in keys.iter_mut() {
        if key.refcount == 0 { garbage.push(id); continue; }

        if_let!{
          Ok(fp) = {
            let data = &key.data;
            key.fp.get_or_insert_with(
              || Ok(Arc::new(data.fingerprint()?))
            )
          };
          else continue;
        }

        use hash_map::Entry::*;
        match fps.entry(fp.clone()) {
          Vacant(ve) => { ve.insert(id); },
          Occupied(mut oe) => {
            error!("ssh key fingerprint collision! \
                    fp={} newid={} oldid={} newdata={:?}",
                   &fp, id, oe.get(), &key.data);
            oe.insert(Id::default());
          },
        }
      }

      for id in garbage { keys.remove(id); }

      fps

    })
  }

  #[throws(AuthKeysManipError)]
  fn write_keys(&self, w: &mut BufWriter<File>) {
    let config = config();

    for (id, key) in &self.keys {
      let fp = match key.fp { Some(Ok(ref fp)) => fp, _ => continue };
      if key.refcount == 0 { continue }
      writeln!(w,
 r#"{},command="{} mgmtchannel-proxy --restrict-ssh {}:{}" {} {}:{}"#, 
               &config.ssh_restrictions,
               &config.ssh_proxy_bin, id, key.nonce,
               &key.data,
               key.refcount, &fp)
        .context("write new auth keys")?;
    }
  }

  // Caller should make sure accounts are saved first, to avoid
  // getting the authkeys_dirty bit wrong.
  #[throws(AuthKeysManipError)]
  fn rewrite_authorized_keys(&mut self) {
    let config = config();
    let path = &config.authorized_keys;
    let tmp = format!("{}.tmp", &path);
    let include = &config.authorized_keys_include;

    let staticf = match File::open(include) {
      Ok(y) => Some(y),
      Err(e) if e.kind() == ErrorKind::NotFound => None,
      Err(e) => throw!(AE::from(e).context(include.clone())
                       .context("open static auth keys")),
    };

    (||{
      let mut f = match File::open(path) {
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(()),
        x => x,
      }.context("open")?;

      let l = BufReader::new(&mut f).lines().next()
        .ok_or_else(|| anyhow!("no first line!"))?
        .context("read first line")?;
      if l == MAGIC_BANNER {
        return Ok(());
      }
      if let Some(staticf) = &staticf {
        let devino = |f: &File| f.metadata().map(|m| (m.dev(), m.ino()));
        if devino(staticf).context("fstat static auth keys")? ==
           devino(&f).context("fstat existing auth keys")? {
             info!("auth keys files hardlinked, doing first install");
             return Ok(());
           }
      }
      Err(anyhow!(
          "first line is not as expected (manually written/edited?) \
           (before first run, make static include be a hardlink to real file)"
      ))
    })()
      .context("check authorized_keys magic/banner")?;

    let mut f = fs::OpenOptions::new()
      .write(true).truncate(true).create(true)
      .mode(0o644)
      .open(&tmp)
      .context("open new auth keys file (.tmp)")?;

    (||{
      let mut f = BufWriter::new(&mut f);
      writeln!(f, "{}", MAGIC_BANNER)?;
      writeln!(f, "# You can edit {:?} instead - that is included here:",
               include)?;
      f.flush()?;
      Ok::<_,io::Error>(())
    })().context("write header (to .tmp)")?;

    if let Some(mut sf) = staticf {
      io::copy(&mut sf, &mut f).context("copy data into new auth keys")?;
      writeln!(f).context("write newline into new auth keys")?;
    }

    let mut f = BufWriter::new(f);
    self.write_keys(&mut f)?;
    f.flush().context("finish writing new auth keys")?;

    fs::rename(&tmp, &path).with_context(|| path.clone())
      .context("install new auth keys")?;

    self.authkeys_dirty = false;
  }
}