summaryrefslogtreecommitdiffstats
path: root/modsign.cxx
blob: 326534ce59023803c41dfcbb341ee42765096e65 (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
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
/*
  This program signs the given file using the named certificate and private
  key in the given certificate database and places the signature in the named
  output file.

  Copyright (C) 2009 Red Hat Inc.

  This file is part of systemtap, and is free software.  You can
  redistribute it and/or modify it under the terms of the GNU General Public
  License as published by the Free Software Foundation; either version 2 of the
  License, or (at your option) any later version.

  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, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "util.h"
#include <iostream>
#include <string>

extern "C" {
#include "nsscommon.h"

#include <nspr.h>
#include <nss.h>
#include <pk11pub.h>
#include <cryptohi.h>

#include <stdio.h>
#include <stdlib.h>

#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
}

using namespace std;

/* Function: int init_cert_db_path (const string &cert_db_path);
 * 
 * Initialize a certificate database at the given path.
 */
static int
init_cert_db_path (const string &cert_db_path) {
  int rc;

  // Generate the certificate and database.
  string cmd = BINDIR "/stap-gen-cert " + cert_db_path;
  rc = system (cmd.c_str ()) == 0;

  return rc;
}

/* Function: int check_cert_db_path (const string &cert_db_path);
 * 
 * Check that the given certificate directory exists and is initialized.
 * Create and/or initialize it otherwise.
 */
static int
check_cert_db_path (const string &cert_db_path) {
  // Does the path exist?
  PRFileInfo fileInfo;
  PRStatus prStatus = PR_GetFileInfo (cert_db_path.c_str(), &fileInfo);
  if (prStatus != PR_SUCCESS || fileInfo.type != PR_FILE_DIRECTORY)
    return init_cert_db_path (cert_db_path);

  // Update the user's cert file if it is old.
  string fname = cert_db_path + "/stap-server.cert";
  prStatus = PR_GetFileInfo (fname.c_str (), &fileInfo);
  if (prStatus == PR_SUCCESS && fileInfo.type == PR_FILE_FILE && fileInfo.size > 0)
    {
      string fname1 = cert_db_path + "/stap.cert";
      prStatus = PR_GetFileInfo (fname1.c_str (), &fileInfo);
      if (prStatus != PR_SUCCESS)
	PR_Rename (fname.c_str (), fname1.c_str ());
      else
	PR_Delete (fname.c_str ());
    }

  return 1; // ok
}

/* Function: char * password_callback()
 * 
 * Purpose: This function is our custom password handler that is called by
 * NSS when retrieving private certs and keys from the database. Returns a
 * pointer to a string that with a password for the database. Password pointer
 * should point to dynamically allocated memory that will be freed later.
 */
static char *
password_callback (PK11SlotInfo *info, PRBool retry, void *arg)
{
  char *passwd = NULL;

  if (! retry && arg)
    passwd = PORT_Strdup((char *)arg);

  return passwd;
}

/* Obtain the certificate and key database password from the given file.  */
static char *
get_password (const string &fileName)
{
  PRFileDesc *local_file_fd;
  PRFileInfo fileInfo;
  PRInt32 numBytesRead;
  PRStatus prStatus;
  PRInt32 i;
  char *password;

  prStatus = PR_GetFileInfo (fileName.c_str(), &fileInfo);
  if (prStatus != PR_SUCCESS || fileInfo.type != PR_FILE_FILE || fileInfo.size < 0)
    {
      cerr << "Could not obtain information on password file " << fileName << "." << endl;
      nssError ();
      return NULL;
    }

  local_file_fd = PR_Open (fileName.c_str(), PR_RDONLY, 0);
  if (local_file_fd == NULL)
    {
      cerr << "Could not open password file " << fileName << "." << endl;
      nssError ();
      return NULL;
    }
      
  password = (char*)PORT_Alloc (fileInfo.size + 1);
  if (! password)
    {
      cerr << "Unable to allocate " << (fileInfo.size + 1) << " bytes." << endl;
      nssError ();
      return NULL;
    }

  numBytesRead = PR_Read (local_file_fd, password, fileInfo.size);
  if (numBytesRead <= 0)
    {
      cerr << "Error reading password file " << fileName << "." << endl;
      nssError ();
      return 0;
    }

  PR_Close (local_file_fd);

  /* Keep only the first line of data.  */
  for (i = 0; i < numBytesRead; ++i)
    {
      if (password[i] == '\n' || password[i] == '\r' || password[i] == '\0')
	break;
    }
  password[i] = '\0';

  return password;
}

static void
sign_it (const string &inputName, const string &outputName, SECKEYPrivateKey *privKey)
{
  unsigned char buffer[4096];
  PRFileDesc *local_file_fd;
  PRUint32 numBytes;
  SECStatus secStatus;
  SGNContext *sgn;
  SECItem signedData;

  /* Set up the signing context.  */
  sgn = SGN_NewContext (SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION, privKey);
  if (! sgn) 
    {
      cerr << "Could not create signing context." << endl;
      nssError ();
      return;
    }
  secStatus = SGN_Begin (sgn);
  if (secStatus != SECSuccess)
    {
      cerr << "Could not initialize signing context." << endl;
      nssError ();
      return;
    }

  /* Now read the data and add it to the signature.  */
  local_file_fd = PR_Open (inputName.c_str(), PR_RDONLY, 0);
  if (local_file_fd == NULL)
    {
      cerr << "Could not open module file " << inputName << "." << endl;
      nssError ();
      return;
    }

  for (;;)
    {
      numBytes = PR_Read (local_file_fd, buffer, sizeof (buffer));
      if (numBytes == 0)
	break;	/* EOF */

      if (numBytes < 0)
	{
	  cerr << "Error reading module file " << inputName << "." << endl;
	  nssError ();
	  return;
	}

      /* Add the data to the signature.  */
      secStatus = SGN_Update (sgn, buffer, numBytes);
      if (secStatus != SECSuccess)
	{
	  cerr << "Error while signing module file " << inputName << "." << endl;
	  nssError ();
	  return;
	}
    }

  PR_Close (local_file_fd);

  /* Complete the signature.  */
  secStatus = SGN_End (sgn, & signedData);
  if (secStatus != SECSuccess)
    {
      cerr << "Could not complete signature of module file " << inputName << "." << endl;
      nssError ();
      return;
    }

  SGN_DestroyContext (sgn, PR_TRUE);

  /* Now write the signed data to the output file.  */
  local_file_fd = PR_Open (outputName.c_str(), PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
			   PR_IRUSR | PR_IWUSR | PR_IRGRP | PR_IWGRP | PR_IROTH);
  if (local_file_fd == NULL)
    {
      cerr << "Could not open signature file " << outputName << "." << endl;
      nssError ();
      return;
    }

  numBytes = PR_Write (local_file_fd, signedData.data, signedData.len);
  if (numBytes < 0 || numBytes != signedData.len)
    {
      cerr << "Error writing to signature file " << outputName << "." << endl;
      nssError ();
      return;
    }

  PR_Close (local_file_fd);
}

int
main(int argc, char **argv)
{
  const char *nickName = "stap-server";
  string module_name;
  string cert_db_path;
  char *password;
  CERTCertificate *cert;
  SECKEYPrivateKey *privKey;
  SECStatus secStatus;
  const char *stap_dir;
  struct passwd *pwd;

  if (argc < 2) {
      cerr << "Module name was not specified." << endl;
      return 1;
  }
  module_name = argv[1];

  if (argc >= 3)
    cert_db_path = argv[2];
  else {
    // Use the default database for this user.
    if (geteuid () == 0)
      cert_db_path = SYSCONFDIR "/systemtap/ssl/server";
    else {
      stap_dir = getenv ("SYSTEMTAP_DIR");
      if (stap_dir == NULL) {
	stap_dir = getenv("HOME");
	if (stap_dir == NULL) {
	  pwd = getpwuid(getuid());
	  if (pwd)
	    stap_dir = pwd->pw_dir;
	  else {
	    cerr << "Unable to determine the certificate database path." << endl;
	    return 1;
	  }
	}
      }
      cert_db_path = stap_dir;
      cert_db_path += "/.systemtap/ssl/server";
    }
  }

  if (! check_cert_db_path (cert_db_path))
    return 1;

  password = get_password (cert_db_path + "/pw");
  if (! password)
    {
      cerr << "Unable to obtain certificate database password." << endl;
      return 1;
    }

  /* Call the NSPR initialization routines. */
  PR_Init (PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);

  /* Set the cert database password callback. */
  PK11_SetPasswordFunc (password_callback);

	/* Initialize NSS. */
  secStatus = NSS_Init (cert_db_path.c_str());
  if (secStatus != SECSuccess)
    {
      cerr << "Unable to initialize nss library." << endl;
      nssError ();
      return 1;
    }

  /* Get own certificate and private key. */
  cert = PK11_FindCertFromNickname (nickName, password);
  if (cert == NULL)
    {
      cerr << "Unable to find certificate with nickname " << nickName
	   << " in " << cert_db_path << "." << endl;
      nssError ();
      return 1;
    }

  privKey = PK11_FindKeyByAnyCert (cert, password);
  if (privKey == NULL)
    {
      cerr << "Unable to obtain private key from the certificate with nickname " << nickName
	   << " in " << cert_db_path << "." << endl;
      nssError ();
      return 1;
    }

  /* Sign the file. */
  sign_it (module_name, module_name + ".sgn", privKey);

  /* Shutdown NSS and exit NSPR gracefully. */
  nssCleanup ();

  return 0;
}

/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */