summaryrefslogtreecommitdiff
path: root/src/pam_xdg.cpp
blob: b3970249d9f7f0f4d42208466183a71fed19829f (plain)
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
#include <cerrno>
#include <cstring>
#include <filesystem>
#include <print>
#include <stdexcept>
#include <string>
#include <string_view>

#include <fcntl.h>
#include <pwd.h>
#include <sys/stat.h>
#include <unistd.h>

#include <security/pam_modules.h>
#include <sqlite3.h>

namespace pam_xdg {

constexpr const std::string_view USER_DIRECTORY = "/run/user";
constexpr const std::string_view DB_PATH = "/run/pam_xdg.db";

void open_db(sqlite3 **db, const std::filesystem::path &path, int flags) {
  auto rc = sqlite3_open_v2(path.c_str(), db, flags, nullptr);

  if (rc != SQLITE_OK) {
    throw std::runtime_error(std::string("failed to open database"));
  }
}

void init_db(sqlite3 *db) {
  auto rc = sqlite3_exec(
      db, "CREATE TABLE IF NOT EXISTS SESSIONS(USERNAME TEXT, LOGINS INT)",
      nullptr, nullptr, nullptr);

  if (rc != SQLITE_OK) {
    throw std::runtime_error(
        std::string("failed to init database: {}", sqlite3_errmsg(db)));
  }
}

void init_session(sqlite3 *db, std::string_view username) {
  const auto *query =
      "INSERT OR IGNORE INTO SESSIONS(USERNAME, LOGINS) VALUES(?, 0)";
  sqlite3_stmt *stmt;
  int rc;

  rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);

  if (rc != SQLITE_OK) {
    throw std::runtime_error(
        std::format("failed to prepare stmt: {}", sqlite3_errmsg(db)));
  }

  rc = sqlite3_bind_text(stmt, 1, username.data(), username.length(), nullptr);

  if (rc != SQLITE_OK) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to bind text to stmt"));
  }

  rc = sqlite3_step(stmt);

  if (rc != SQLITE_DONE) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to step stmt"));
  }

  sqlite3_finalize(stmt);
}

void record_login(sqlite3 *db, std::string_view username) {
  const auto *query = "UPDATE SESSIONS SET LOGINS=LOGINS+1 WHERE USERNAME=?";
  sqlite3_stmt *stmt;
  int rc;

  rc = sqlite3_prepare_v2(db, query, -1, &stmt, nullptr);

  if (rc != SQLITE_OK) {
    throw std::runtime_error(
        std::string("failed to prepare stmt: {}", sqlite3_errmsg(db)));
  }

  rc = sqlite3_bind_text(stmt, 1, username.data(), username.length(), nullptr);

  if (rc != SQLITE_OK) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to bind text"));
  }

  rc = sqlite3_step(stmt);

  if (rc != SQLITE_DONE) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to step stmt"));
  }

  sqlite3_finalize(stmt);
}

void record_logout(sqlite3 *db, std::string_view username) {
  const auto *query = "UPDATE SESSIONS SET LOGINS=LOGINS-1 WHERE USERNAME=?";
  sqlite3_stmt *stmt;
  int rc;

  rc = sqlite3_prepare_v2(db, query, -1, &stmt, nullptr);

  if (rc != SQLITE_OK) {
    throw std::runtime_error(
        std::string("failed to prepare stmt: {}", sqlite3_errmsg(db)));
  }

  rc = sqlite3_bind_text(stmt, 1, username.data(), username.length(), nullptr);

  if (rc != SQLITE_OK) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to bind text"));
  }

  rc = sqlite3_step(stmt);

  if (rc != SQLITE_DONE) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to step stmt"));
  }

  sqlite3_finalize(stmt);
}

bool is_logged_in(sqlite3 *db, std::string_view username) {
  const auto *query = "SELECT LOGINS FROM SESSIONS WHERE USERNAME=?";
  sqlite3_stmt *stmt;
  int rc;

  rc = sqlite3_prepare_v2(db, query, -1, &stmt, nullptr);

  if (rc != SQLITE_OK) {
    throw std::runtime_error(
        std::format("failed to prepare stmt: {}", sqlite3_errmsg(db)));
  }

  rc = sqlite3_bind_text(stmt, 1, username.data(), username.length(), nullptr);

  if (rc != SQLITE_OK) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to bind text"));
  }

  rc = sqlite3_step(stmt);

  if (rc != SQLITE_ROW) {
    sqlite3_finalize(stmt);
    throw std::runtime_error(std::string("failed to step stmt"));
  }

  int logins = sqlite3_column_int(stmt, 0);

  sqlite3_finalize(stmt);

  return (logins > 0);
}

void touch(const std::filesystem::path &path, int mode) {
  auto fd = creat(path.c_str(), mode);

  if (fd == -1) {
    throw std::runtime_error(std::format("failed to touch file: {} {}",
                                         path.c_str(), std::strerror(errno)));
  }

  close(fd);
}

void create_directory(const std::filesystem::path &path, std::uint16_t owner,
                      int mode) {
  int rc;

  rc = mkdir(path.c_str(), mode);

  if (rc == -1) {
    throw std::runtime_error(std::format("failed to mkdir: {} {}", path.c_str(),
                                         std::strerror(errno)));
  }

  rc = chown(path.c_str(), owner, owner);

  if (rc == -1) {
    throw std::runtime_error(std::format("failed to chown: {} {}", path.c_str(),
                                         std::strerror(errno)));
  }
}
} // namespace pam_xdg

extern "C" int pam_sm_open_session(pam_handle_t *pamh,
                                   [[gnu::unused]] int flags,
                                   [[gnu::unused]] int argc,
                                   [[gnu::unused]] const char **argv) {

  const void *data;
  if (pam_get_item(pamh, PAM_USER, &data) != PAM_SUCCESS) {
    std::println(stderr, "failed to get pam item PAM_USER");
    return PAM_SESSION_ERR;
  }
  auto *username = static_cast<const char *>(data);

  if (std::string_view(username) == "root") {
    return 0;
  }

  auto passwd = getpwnam(username);
  auto uid = passwd->pw_uid;

  auto xdg_runtime_dir =
      std::filesystem::path(pam_xdg::USER_DIRECTORY) / std::format("{}", uid);

  sqlite3 *db;

  try {
    if (!std::filesystem::exists(pam_xdg::DB_PATH)) {
      pam_xdg::touch(pam_xdg::DB_PATH, 0600);

      pam_xdg::open_db(&db, pam_xdg::DB_PATH,
                       SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE);

      pam_xdg::init_db(db);
    } else {
      pam_xdg::open_db(&db, pam_xdg::DB_PATH, SQLITE_OPEN_READWRITE);
    }

    pam_xdg::init_session(db, username);

    if (!pam_xdg::is_logged_in(db, username)) {
      if (!std::filesystem::exists(pam_xdg::USER_DIRECTORY)) {
        pam_xdg::create_directory(pam_xdg::USER_DIRECTORY, 0, 0755);
      }
      if (!std::filesystem::is_directory(pam_xdg::USER_DIRECTORY)) {
        throw std::runtime_error(
            std::format("{} is not a directory", pam_xdg::USER_DIRECTORY));
      }

      pam_xdg::create_directory(std::filesystem::path(pam_xdg::USER_DIRECTORY) /
                                    std::format("{}", uid),
                                uid, 0700);
    }

    pam_xdg::record_login(db, username);

    auto envvar = std::format("XDG_RUNTIME_DIR={}", xdg_runtime_dir.c_str());
    if (pam_putenv(pamh, envvar.c_str()) != PAM_SUCCESS) {
      throw std::runtime_error(std::format("failed to putenv: {}", envvar));
    }

  } catch (const std::exception &e) {
    std::println(stderr, "{}", e.what());

    return PAM_SESSION_ERR;
  }

  return PAM_SUCCESS;
}

extern "C" int pam_sm_close_session(pam_handle_t *pam,
                                    [[gnu::unused]] int flags,
                                    [[gnu::unused]] int argc,
                                    [[gnu::unused]] const char **argv) {

  const void *data;
  if (pam_get_item(pam, PAM_USER, &data) != PAM_SUCCESS) {
    std::println(stderr, "failed to get pam item PAM_USER");
    return PAM_SESSION_ERR;
  }
  auto *username = static_cast<const char *>(data);

  if (std::string_view(username) == "root") {
    return 0;
  }

  auto passwd = getpwnam(username);
  auto uid = passwd->pw_uid;

  auto xdg_runtime_dir =
      std::filesystem::path(pam_xdg::USER_DIRECTORY) / std::format("{}", uid);

  sqlite3 *db;

  try {
    pam_xdg::open_db(&db, pam_xdg::DB_PATH, SQLITE_OPEN_READWRITE);

    pam_xdg::record_logout(db, username);

    if (!pam_xdg::is_logged_in(db, username)) {
      std::filesystem::remove_all(xdg_runtime_dir);
    }
  } catch (const std::exception &e) {
    std::println(stderr, "{}", e.what());

    return PAM_SESSION_ERR;
  }

  return PAM_SUCCESS;
}