repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
null |
jax-main/jaxlib/gpu/blas_kernels.h
|
/* Copyright 2019 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef JAXLIB_GPU_BLAS_KERNELS_H_
#define JAXLIB_GPU_BLAS_KERNELS_H_
#include <cstddef>
#include "jaxlib/gpu/vendor.h"
#include "xla/service/custom_call_status.h"
namespace jax {
namespace JAX_GPU_NAMESPACE {
// Set of types known to Cusolver.
enum class BlasType {
F32,
F64,
C64,
C128,
};
// Batched LU decomposition: getrfbatched
struct GetrfBatchedDescriptor {
BlasType type;
int batch, n;
};
void GetrfBatched(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// Batched QR decomposition: geqrfbatched
struct GeqrfBatchedDescriptor {
BlasType type;
int batch, m, n;
};
void GeqrfBatched(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
} // namespace JAX_GPU_NAMESPACE
} // namespace jax
#endif // JAXLIB_GPU_BLAS_KERNELS_H_
| 1,550 | 25.288136 | 80 |
h
|
null |
jax-main/jaxlib/gpu/gpu_kernel_helpers.h
|
/* Copyright 2019 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef JAXLIB_GPU_GPU_KERNEL_HELPERS_H_
#define JAXLIB_GPU_GPU_KERNEL_HELPERS_H_
#include <memory>
#include "absl/base/optimization.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "jaxlib/gpu/vendor.h"
#define JAX_AS_STATUS(expr) \
jax::JAX_GPU_NAMESPACE::AsStatus(expr, __FILE__, __LINE__, #expr)
#define JAX_THROW_IF_ERROR(expr) \
{ \
auto s___ = (expr); \
if (ABSL_PREDICT_FALSE(!s___.ok())) \
throw std::runtime_error(std::string(s___.message())); \
}
#define JAX_RETURN_IF_ERROR(expr) \
{ \
auto s___ = (expr); \
if (ABSL_PREDICT_FALSE(!s___.ok())) return s___; \
}
#define JAX_ASSIGN_OR_RETURN(lhs, expr) \
auto s___ = (expr); \
if (ABSL_PREDICT_FALSE(!s___.ok())) { \
return s___.status(); \
} \
lhs = (*std::move(s___))
namespace jax {
namespace JAX_GPU_NAMESPACE {
// Used via JAX_AS_STATUS(expr) macro.
absl::Status AsStatus(gpuError_t error, const char* file, std::int64_t line,
const char* expr);
absl::Status AsStatus(gpusolverStatus_t status, const char* file,
std::int64_t line, const char* expr);
absl::Status AsStatus(gpusparseStatus_t status, const char* file,
std::int64_t line, const char* expr);
absl::Status AsStatus(gpublasStatus_t status, const char* file,
std::int64_t line, const char* expr);
#ifdef JAX_GPU_CUDA
absl::Status AsStatus(CUresult error, const char* file, std::int64_t line,
const char* expr);
#endif
// Builds an array of pointers to each array in a batch, in device memory.
// Caution: the return value must be kept alive (e.g., via a stream
// synchronization) until the copy enqueued by MakeBatchPointers on `stream`
// completes.
absl::StatusOr<std::unique_ptr<void*[]>> MakeBatchPointers(gpuStream_t stream,
void* buffer,
void* dev_ptrs,
int batch,
int batch_elem_size);
} // namespace JAX_GPU_NAMESPACE
} // namespace jax
#endif // JAXLIB_GPU_GPU_KERNEL_HELPERS_H_
| 3,196 | 38.9625 | 80 |
h
|
null |
jax-main/jaxlib/gpu/lu_pivot_kernels.h
|
/* Copyright 2021 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef JAXLIB_GPU_LU_PIVOT_KERNELS_H_
#define JAXLIB_GPU_LU_PIVOT_KERNELS_H_
#include <cstddef>
#include <string>
#include "jaxlib/gpu/vendor.h"
#include "xla/service/custom_call_status.h"
namespace jax {
namespace JAX_GPU_NAMESPACE {
struct LuPivotsToPermutationDescriptor {
std::int64_t batch_size;
std::int32_t pivot_size;
std::int32_t permutation_size;
};
void LaunchLuPivotsToPermutationKernel(
gpuStream_t stream, void** buffers,
LuPivotsToPermutationDescriptor descriptor);
void LuPivotsToPermutation(gpuStream_t stream, void** buffers,
const char* opaque, size_t opaque_len,
XlaCustomCallStatus* status);
} // namespace JAX_GPU_NAMESPACE
} // namespace jax
#endif // JAXLIB_GPU_LU_PIVOT_KERNELS_H_
| 1,428 | 30.065217 | 80 |
h
|
null |
jax-main/jaxlib/gpu/prng_kernels.h
|
/* Copyright 2019 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef JAXLIB_GPU_PRNG_KERNELS_H_
#define JAXLIB_GPU_PRNG_KERNELS_H_
#include <cstddef>
#include <string>
#include "jaxlib/gpu/vendor.h"
#include "xla/service/custom_call_status.h"
namespace jax {
namespace JAX_GPU_NAMESPACE {
struct ThreeFry2x32Descriptor {
std::int64_t n; // If -1 then the length is passed as a 5th operand
};
void LaunchThreeFry2x32Kernel(gpuStream_t stream, void** buffers,
ThreeFry2x32Descriptor descriptor);
void ThreeFry2x32(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
} // namespace JAX_GPU_NAMESPACE
} // namespace jax
#endif // JAXLIB_GPU_PRNG_KERNELS_H_
| 1,349 | 31.142857 | 80 |
h
|
null |
jax-main/jaxlib/gpu/rnn_kernels.h
|
/* Copyright 2022 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef JAXLIB_GPU_RNN_KERNELS_H_
#define JAXLIB_GPU_RNN_KERNELS_H_
#include "absl/status/statusor.h"
#include "jaxlib/gpu/vendor.h"
#include "xla/service/custom_call_status.h"
namespace jax {
namespace JAX_GPU_NAMESPACE {
// Compile-time info passed as `opaque` to custom kernel.
struct RnnDescriptor {
int input_size;
int hidden_size;
int num_layers;
int batch_size;
int max_seq_length;
float dropout;
bool bidirectional;
int workspace_size;
int reserve_space_size;
};
// Return (workspace size, reserve space size).
absl::StatusOr<std::pair<int, int>> RnnComputeWorkspaceReserveSpaceSizes(
int input_size, int hidden_size, int num_layers, int batch_size,
int max_seq_length, float dropout, bool bidirectional);
void RNNForward(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
void RNNBackward(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
} // namespace JAX_GPU_NAMESPACE
} // namespace jax
#endif // JAXLIB_GPU_RNN_KERNELS_H_
| 1,757 | 31.555556 | 80 |
h
|
null |
jax-main/jaxlib/gpu/solver_kernels.h
|
/* Copyright 2019 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef JAXLIB_CUSOLVER_KERNELS_H_
#define JAXLIB_CUSOLVER_KERNELS_H_
#include "absl/status/statusor.h"
#include "jaxlib/gpu/vendor.h"
#include "jaxlib/handle_pool.h"
#include "xla/service/custom_call_status.h"
#ifdef JAX_GPU_CUDA
#include "third_party/gpus/cuda/include/cusolverSp.h"
#endif // JAX_GPU_CUDA
namespace jax {
using SolverHandlePool = HandlePool<gpusolverDnHandle_t, gpuStream_t>;
template <>
absl::StatusOr<SolverHandlePool::Handle> SolverHandlePool::Borrow(
gpuStream_t stream);
#ifdef JAX_GPU_CUDA
using SpSolverHandlePool = HandlePool<cusolverSpHandle_t, gpuStream_t>;
template <>
absl::StatusOr<SpSolverHandlePool::Handle> SpSolverHandlePool::Borrow(
gpuStream_t stream);
#endif // JAX_GPU_CUDA
namespace JAX_GPU_NAMESPACE {
// Set of types known to Cusolver.
enum class SolverType {
F32,
F64,
C64,
C128,
};
// getrf: LU decomposition
struct GetrfDescriptor {
SolverType type;
int batch, m, n, lwork;
};
void Getrf(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// geqrf: QR decomposition
struct GeqrfDescriptor {
SolverType type;
int batch, m, n, lwork;
};
void Geqrf(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
#ifdef JAX_GPU_CUDA
// csrlsvpr: Linear system solve via Sparse QR
struct CsrlsvqrDescriptor {
SolverType type;
int n, nnz, reorder;
double tol;
};
void Csrlsvqr(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
#endif // JAX_GPU_CUDA
// orgqr/ungqr: apply elementary Householder transformations
struct OrgqrDescriptor {
SolverType type;
int batch, m, n, k, lwork;
};
void Orgqr(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// Symmetric (Hermitian) eigendecomposition, QR algorithm: syevd/heevd
struct SyevdDescriptor {
SolverType type;
gpusolverFillMode_t uplo;
int batch, n; // batch may be -1 in which case it is passed as operand.
int lwork;
};
void Syevd(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// Symmetric (Hermitian) eigendecomposition, Jacobi algorithm: syevj/heevj
// Supports batches of matrices up to size 32.
struct SyevjDescriptor {
SolverType type;
gpusolverFillMode_t uplo;
int batch, n;
int lwork;
};
void Syevj(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// Singular value decomposition using QR algorithm: gesvd
struct GesvdDescriptor {
SolverType type;
int batch, m, n;
int lwork;
signed char jobu, jobvt;
};
void Gesvd(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
#ifdef JAX_GPU_CUDA
// Singular value decomposition using Jacobi algorithm: gesvdj
struct GesvdjDescriptor {
SolverType type;
int batch, m, n;
int lwork;
gpusolverEigMode_t jobz;
int econ;
};
void Gesvdj(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
#endif // JAX_GPU_CUDA
// sytrd/hetrd: Reduction of a symmetric (Hermitian) matrix to tridiagonal form.
struct SytrdDescriptor {
SolverType type;
gpusolverFillMode_t uplo;
int batch, n, lda, lwork;
};
void Sytrd(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
} // namespace JAX_GPU_NAMESPACE
} // namespace jax
#endif // JAXLIB_CUSOLVER_KERNELS_H_
| 4,322 | 24.579882 | 80 |
h
|
null |
jax-main/jaxlib/gpu/sparse_kernels.h
|
/* Copyright 2021 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef JAXLIB_GPU_SPARSE_KERNELS_H_
#define JAXLIB_GPU_SPARSE_KERNELS_H_
#include <algorithm>
#include <cstdint>
#include <stdexcept>
#include <utility>
#include <vector>
#include "absl/status/statusor.h"
#include "jaxlib/gpu/vendor.h"
#include "jaxlib/handle_pool.h"
#include "xla/service/custom_call_status.h"
namespace jax {
using SparseHandlePool = HandlePool<gpusparseHandle_t, gpuStream_t>;
template <>
/*static*/ absl::StatusOr<SparseHandlePool::Handle> SparseHandlePool::Borrow(
gpuStream_t stream);
namespace JAX_GPU_NAMESPACE {
union SparseConst {
int8_t i8[2];
int16_t i16[2];
int32_t i32[2];
int64_t i64[2];
uint8_t u8[2];
uint16_t u16[2];
uint32_t u32[2];
uint64_t u64[2];
float f32[2];
double f64[2];
};
SparseConst ConstZero(gpuDataType type);
SparseConst ConstOne(gpuDataType type);
struct SparseMatDescriptor {
gpuDataType value_type;
gpusparseIndexType_t index_type;
int rows, cols, nnz;
int batch_count = 1;
int batch_stride = 0;
};
struct DenseMatDescriptor {
gpuDataType type;
int rows, cols;
int batch_count = 1;
int batch_stride = 0;
};
struct DenseVecDescriptor {
gpuDataType type;
int size;
};
#if JAX_GPU_HAVE_SPARSE
// CsrToDense: Convert CSR matrix to dense matrix
void CsrToDense(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// CsrFromDense: Convert dense matrix to CSR matrix
void CsrFromDense(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// CsrMatvec: Product of CSR matrix and dense vector.
struct CsrMatvecDescriptor {
SparseMatDescriptor A;
DenseVecDescriptor x, y;
gpusparseOperation_t op;
};
void CsrMatvec(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// CsrMatmat: Product of CSR matrix and dense matrix.
struct CsrMatmatDescriptor {
SparseMatDescriptor A;
DenseMatDescriptor B, C;
gpusparseOperation_t op_A;
};
void CsrMatmat(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// CooToDense: Convert COO matrix to dense matrix
void CooToDense(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// CooFromDense: Convert dense matrix to COO matrix
void CooFromDense(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// CooMatvec: Product of COO matrix and dense vector.
struct CooMatvecDescriptor {
SparseMatDescriptor A;
DenseVecDescriptor x, y;
gpusparseOperation_t op;
};
void CooMatvec(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
// CooMatmat: Product of COO matrix and dense matrix.
struct CooMatmatDescriptor {
SparseMatDescriptor A;
DenseMatDescriptor B, C;
gpusparseOperation_t op_A;
};
void CooMatmat(gpuStream_t stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
#endif // JAX_GPU_HAVE_SPARSE
struct Gtsv2Descriptor {
int m, n, ldb;
};
void gtsv2_f32(gpuStream_t stream, void** buffers, const char* opaque,
std::size_t opaque_len, XlaCustomCallStatus* status);
void gtsv2_f64(gpuStream_t stream, void** buffers, const char* opaque,
std::size_t opaque_len, XlaCustomCallStatus* status);
} // namespace JAX_GPU_NAMESPACE
} // namespace jax
#endif // JAXLIB_GPU_SPARSE_KERNELS_H_
| 4,282 | 26.455128 | 80 |
h
|
null |
jax-main/jaxlib/gpu/triton_kernels.h
|
#ifndef JAXLIB_GPU_TRITON_H_
#define JAXLIB_GPU_TRITON_H_
#include <cstdint>
#include <memory>
#include <string>
#include <tuple>
#include <variant>
#include <vector>
#include "absl/cleanup/cleanup.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "jaxlib/gpu/triton.pb.h"
#include "jaxlib/gpu/vendor.h"
#include "xla/service/custom_call_status.h"
namespace jax::JAX_GPU_NAMESPACE {
void TritonKernelCall(CUstream stream, void** buffers, const char* opaque,
size_t opaque_len, XlaCustomCallStatus* status);
class ModuleImage;
class Kernel {
public:
Kernel(std::string kernel_name, uint32_t num_warps, uint32_t shared_mem_bytes,
std::string ptx, std::string ttir, int compute_capability);
absl::Status Launch(CUstream stream, uint32_t grid[3], void** params);
static Kernel FromProto(const jax_triton::TritonKernel& proto);
jax_triton::TritonKernel ToProto() const;
private:
std::string kernel_name_;
uint32_t block_dim_x_;
uint32_t shared_mem_bytes_;
std::string ptx_;
std::string ttir_;
int compute_capability_;
ModuleImage* module_image_ = nullptr;
};
class KernelCall {
public:
struct Parameter {
struct Array {
size_t bytes_to_zero;
size_t ptr_divisibility;
};
static absl::StatusOr<Parameter> FromProto(
const jax_triton::TritonKernelCall_Parameter& proto);
jax_triton::TritonKernelCall_Parameter ToProto() const;
std::variant<Array, bool, int32_t, uint32_t, int64_t, uint64_t> value;
};
KernelCall(Kernel kernel, uint32_t grid_0, uint32_t grid_1, uint32_t grid_2,
std::vector<Parameter> parameters);
absl::Status Launch(CUstream stream, void** buffers);
static absl::StatusOr<KernelCall> FromProto(
const jax_triton::TritonKernelCall& proto);
jax_triton::TritonKernelCall ToProto() const;
private:
Kernel kernel_;
uint32_t grid_[3];
std::vector<Parameter> parameters_;
};
class AutotunedKernelCall {
public:
struct Config {
KernelCall kernel_call;
std::string description;
};
AutotunedKernelCall(
std::string name, std::vector<Config> configs,
std::vector<std::tuple<size_t, size_t, size_t>> input_output_aliases);
static absl::StatusOr<KernelCall> Autotune(AutotunedKernelCall kernel_call,
CUstream stream, void** buffers);
static absl::StatusOr<AutotunedKernelCall> FromProto(
const jax_triton::TritonAutotunedKernelCall& proto);
jax_triton::TritonAutotunedKernelCall ToProto() const;
private:
std::string name_;
std::vector<Config> configs_;
// (input buffer idx, output buffer idx, size)
std::vector<std::tuple<size_t, size_t, size_t>> input_output_aliases_;
};
absl::StatusOr<std::string> ZlibUncompress(absl::string_view compressed);
} // namespace jax::JAX_GPU_NAMESPACE
#endif // JAXLIB_GPU_TRITON_H_
| 2,937 | 26.457944 | 80 |
h
|
null |
jax-main/jaxlib/gpu/vendor.h
|
/* Copyright 2022 The JAX Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This header is a shim that manages differences between CUDA and ROCM APIs.
// Jaxlib GPU kernels can be compiled for either CUDA or ROCM by defining
// JAX_GPU_CUDA or JAX_GPU_HIP respectively.
#ifndef JAXLIB_GPU_VENDOR_H_
#define JAXLIB_GPU_VENDOR_H_
#if defined(JAX_GPU_CUDA)
#include "third_party/gpus/cuda/include/cuComplex.h"
#include "third_party/gpus/cuda/include/cublas_v2.h"
#include "third_party/gpus/cuda/include/cuda.h"
#include "third_party/gpus/cuda/include/cuda_runtime_api.h"
#include "third_party/gpus/cuda/include/cusolverDn.h"
#include "third_party/gpus/cuda/include/cusparse.h"
#include "third_party/gpus/cudnn/cudnn.h"
// Some sparse functionality is only available in CUSPARSE 11.3 or newer.
#define JAX_GPU_HAVE_SPARSE (CUSPARSE_VERSION >= 11300)
// CUDA-11.8 introduces FP8 E4M3/E5M2 types.
#define JAX_GPU_HAVE_FP8 (CUDA_VERSION >= 11080)
#if JAX_GPU_HAVE_FP8
#include "third_party/gpus/cuda/include/cuda_fp8.h"
#endif
// cuSPARSE generic APIs are not supported on Windows until 11.0
// cusparseIndexType_t is used in very limited scope so manually define will
// workaround compiling issue without harm.
#if defined(_WIN32) && (CUSPARSE_VERSION < 11000)
typedef enum {
CUSPARSE_INDEX_16U = 1,
CUSPARSE_INDEX_32I = 2,
CUSPARSE_INDEX_64I = 3
} cusparseIndexType_t;
#endif
#define JAX_GPU_NAMESPACE cuda
#define JAX_GPU_PREFIX "cu"
typedef cuComplex gpuComplex;
typedef cuDoubleComplex gpuDoubleComplex;
typedef cuComplex gpublasComplex;
typedef cuDoubleComplex gpublasDoubleComplex;
typedef cublasFillMode_t gpusolverFillMode_t;
typedef cublasStatus_t gpublasStatus_t;
typedef cublasHandle_t gpublasHandle_t;
typedef cudaDataType gpuDataType;
typedef cudaStream_t gpuStream_t;
typedef cudaError_t gpuError_t;
typedef cudnnHandle_t gpudnnHandle_t;
typedef cudnnStatus_t gpudnnStatus_t;
typedef cusolverDnHandle_t gpusolverDnHandle_t;
typedef cusolverStatus_t gpusolverStatus_t;
typedef cusolverEigMode_t gpusolverEigMode_t;
typedef syevjInfo gpuSyevjInfo;
typedef syevjInfo_t gpuSyevjInfo_t;
typedef cusparseIndexType_t gpusparseIndexType_t;
typedef cusparseHandle_t gpusparseHandle_t;
typedef cusparseOperation_t gpusparseOperation_t;
typedef cusparseStatus_t gpusparseStatus_t;
typedef cusparseSpMatDescr_t gpusparseSpMatDescr_t;
typedef cusparseDnMatDescr_t gpusparseDnMatDescr_t;
typedef cusparseDnVecDescr_t gpusparseDnVecDescr_t;
#define GPU_C_16F CUDA_C_16F
#define GPU_R_16F CUDA_R_16F
#define GPU_C_32F CUDA_C_32F
#define GPU_R_32F CUDA_R_32F
#define GPU_C_64F CUDA_C_64F
#define GPU_R_64F CUDA_R_64F
#define gpublasCreate cublasCreate
#define gpublasSetStream cublasSetStream
#define gpublasSgeqrfBatched cublasSgeqrfBatched
#define gpublasDgeqrfBatched cublasDgeqrfBatched
#define gpublasCgeqrfBatched cublasCgeqrfBatched
#define gpublasZgeqrfBatched cublasZgeqrfBatched
#define gpublasSgetrfBatched cublasSgetrfBatched
#define gpublasDgetrfBatched cublasDgetrfBatched
#define gpublasCgetrfBatched cublasCgetrfBatched
#define gpublasZgetrfBatched cublasZgetrfBatched
#define GPUBLAS_STATUS_SUCCESS CUBLAS_STATUS_SUCCESS
#define gpudnnCreate cudnnCreate
#define gpudnnSetStream cudnnSetStream
#define GPUDNN_STATUS_SUCCESS CUDNN_STATUS_SUCCESS
#define gpusolverDnCreate cusolverDnCreate
#define gpusolverDnSetStream cusolverDnSetStream
#define gpusolverDnCreateSyevjInfo cusolverDnCreateSyevjInfo
#define gpusolverDnDestroySyevjInfo cusolverDnDestroySyevjInfo
#define gpusolverDnSgeqrf cusolverDnSgeqrf
#define gpusolverDnDgeqrf cusolverDnDgeqrf
#define gpusolverDnCgeqrf cusolverDnCgeqrf
#define gpusolverDnZgeqrf cusolverDnZgeqrf
#define gpusolverDnSgeqrf_bufferSize cusolverDnSgeqrf_bufferSize
#define gpusolverDnDgeqrf_bufferSize cusolverDnDgeqrf_bufferSize
#define gpusolverDnCgeqrf_bufferSize cusolverDnCgeqrf_bufferSize
#define gpusolverDnZgeqrf_bufferSize cusolverDnZgeqrf_bufferSize
#define gpusolverDnSgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
cusolverDnSgetrf(h, m, n, a, lda, work, ipiv, info)
#define gpusolverDnDgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
cusolverDnDgetrf(h, m, n, a, lda, work, ipiv, info)
#define gpusolverDnCgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
cusolverDnCgetrf(h, m, n, a, lda, work, ipiv, info)
#define gpusolverDnZgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
cusolverDnZgetrf(h, m, n, a, lda, work, ipiv, info)
#define gpusolverDnSgetrf_bufferSize cusolverDnSgetrf_bufferSize
#define gpusolverDnDgetrf_bufferSize cusolverDnDgetrf_bufferSize
#define gpusolverDnCgetrf_bufferSize cusolverDnCgetrf_bufferSize
#define gpusolverDnZgetrf_bufferSize cusolverDnZgetrf_bufferSize
#define gpusolverDnSorgqr cusolverDnSorgqr
#define gpusolverDnDorgqr cusolverDnDorgqr
#define gpusolverDnCungqr cusolverDnCungqr
#define gpusolverDnZungqr cusolverDnZungqr
#define gpusolverDnSorgqr_bufferSize cusolverDnSorgqr_bufferSize
#define gpusolverDnDorgqr_bufferSize cusolverDnDorgqr_bufferSize
#define gpusolverDnCungqr_bufferSize cusolverDnCungqr_bufferSize
#define gpusolverDnZungqr_bufferSize cusolverDnZungqr_bufferSize
#define gpusolverDnSsyevd cusolverDnSsyevd
#define gpusolverDnDsyevd cusolverDnDsyevd
#define gpusolverDnCheevd cusolverDnCheevd
#define gpusolverDnZheevd cusolverDnZheevd
#define gpusolverDnSsyevd_bufferSize cusolverDnSsyevd_bufferSize
#define gpusolverDnDsyevd_bufferSize cusolverDnDsyevd_bufferSize
#define gpusolverDnCheevd_bufferSize cusolverDnCheevd_bufferSize
#define gpusolverDnZheevd_bufferSize cusolverDnZheevd_bufferSize
#define gpusolverDnSsyevj cusolverDnSsyevj
#define gpusolverDnDsyevj cusolverDnDsyevj
#define gpusolverDnCheevj cusolverDnCheevj
#define gpusolverDnZheevj cusolverDnZheevj
#define gpusolverDnSsyevj_bufferSize cusolverDnSsyevj_bufferSize
#define gpusolverDnDsyevj_bufferSize cusolverDnDsyevj_bufferSize
#define gpusolverDnCheevj_bufferSize cusolverDnCheevj_bufferSize
#define gpusolverDnZheevj_bufferSize cusolverDnZheevj_bufferSize
#define gpusolverDnSsyevjBatched cusolverDnSsyevjBatched
#define gpusolverDnDsyevjBatched cusolverDnDsyevjBatched
#define gpusolverDnCheevjBatched cusolverDnCheevjBatched
#define gpusolverDnZheevjBatched cusolverDnZheevjBatched
#define gpusolverDnSsyevjBatched_bufferSize cusolverDnSsyevjBatched_bufferSize
#define gpusolverDnDsyevjBatched_bufferSize cusolverDnDsyevjBatched_bufferSize
#define gpusolverDnCheevjBatched_bufferSize cusolverDnCheevjBatched_bufferSize
#define gpusolverDnZheevjBatched_bufferSize cusolverDnZheevjBatched_bufferSize
#define gpusolverDnSgesvd cusolverDnSgesvd
#define gpusolverDnDgesvd cusolverDnDgesvd
#define gpusolverDnCgesvd cusolverDnCgesvd
#define gpusolverDnZgesvd cusolverDnZgesvd
#define gpusolverDnSgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
cusolverDnSgesvd_bufferSize(h, m, n, lwork)
#define gpusolverDnDgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
cusolverDnDgesvd_bufferSize(h, m, n, lwork)
#define gpusolverDnCgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
cusolverDnCgesvd_bufferSize(h, m, n, lwork)
#define gpusolverDnZgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
cusolverDnZgesvd_bufferSize(h, m, n, lwork)
#define gpusolverDnSsytrd_bufferSize cusolverDnSsytrd_bufferSize
#define gpusolverDnDsytrd_bufferSize cusolverDnDsytrd_bufferSize
#define gpusolverDnChetrd_bufferSize cusolverDnChetrd_bufferSize
#define gpusolverDnZhetrd_bufferSize cusolverDnZhetrd_bufferSize
#define gpusolverDnSsytrd cusolverDnSsytrd
#define gpusolverDnDsytrd cusolverDnDsytrd
#define gpusolverDnChetrd cusolverDnChetrd
#define gpusolverDnZhetrd cusolverDnZhetrd
#define GPUSOLVER_FILL_MODE_LOWER CUBLAS_FILL_MODE_LOWER
#define GPUSOLVER_FILL_MODE_UPPER CUBLAS_FILL_MODE_UPPER
#define GPUSOLVER_EIG_MODE_VECTOR CUSOLVER_EIG_MODE_VECTOR
#define GPUSOLVER_STATUS_SUCCESS CUSOLVER_STATUS_SUCCESS
#define gpusparseCooSetStridedBatch cusparseCooSetStridedBatch
#define gpusparseCreate cusparseCreate
#define gpusparseCreateCoo cusparseCreateCoo
#define gpusparseCreateCsr cusparseCreateCsr
#define gpusparseCreateDnMat cusparseCreateDnMat
#define gpusparseCreateDnVec cusparseCreateDnVec
#define gpusparseDenseToSparse_analysis cusparseDenseToSparse_analysis
#define gpusparseDenseToSparse_bufferSize cusparseDenseToSparse_bufferSize
#define gpusparseDenseToSparse_convert cusparseDenseToSparse_convert
#define gpusparseDestroySpMat cusparseDestroySpMat
#define gpusparseDestroyDnMat cusparseDestroyDnMat
#define gpusparseDestroyDnVec cusparseDestroyDnVec
#define gpusparseDnMatSetStridedBatch cusparseDnMatSetStridedBatch
#define gpusparseSetStream cusparseSetStream
#define gpusparseSparseToDense cusparseSparseToDense
#define gpusparseSparseToDense_bufferSize cusparseSparseToDense_bufferSize
#define gpusparseSpMM cusparseSpMM
#define gpusparseSpMM_bufferSize cusparseSpMM_bufferSize
#define gpusparseSpMV cusparseSpMV
#define gpusparseSpMV_bufferSize cusparseSpMV_bufferSize
#define gpusparseSgtsv2 cusparseSgtsv2
#define gpusparseDgtsv2 cusparseDgtsv2
#define gpusparseSgtsv2_bufferSizeExt cusparseSgtsv2_bufferSizeExt
#define gpusparseDgtsv2_bufferSizeExt cusparseDgtsv2_bufferSizeExt
#define GPUSPARSE_INDEX_16U CUSPARSE_INDEX_16U
#define GPUSPARSE_INDEX_32I CUSPARSE_INDEX_32I
#define GPUSPARSE_INDEX_64I CUSPARSE_INDEX_64I
#define GPUSPARSE_DENSETOSPARSE_ALG_DEFAULT CUSPARSE_DENSETOSPARSE_ALG_DEFAULT
#define GPUSPARSE_INDEX_BASE_ZERO CUSPARSE_INDEX_BASE_ZERO
// Use CUSPARSE_SPMV_COO_ALG2 and CUSPARSE_SPMV_CSR_ALG2 for SPMV and
// use CUSPARSE_SPMM_COO_ALG2 and CUSPARSE_SPMM_CSR_ALG3 for SPMM, which
// provide deterministic (bit-wise) results for each run. These indexing modes
// are fully supported (both row- and column-major inputs) in CUSPARSE 11.7.1
// and newer (which was released as part of CUDA 11.8)
#if CUSPARSE_VERSION > 11700
#define GPUSPARSE_SPMV_COO_ALG CUSPARSE_SPMV_COO_ALG2
#define GPUSPARSE_SPMV_CSR_ALG CUSPARSE_SPMV_CSR_ALG2
#define GPUSPARSE_SPMM_COO_ALG CUSPARSE_SPMM_COO_ALG2
#define GPUSPARSE_SPMM_CSR_ALG CUSPARSE_SPMM_CSR_ALG3
#else
#define GPUSPARSE_SPMV_COO_ALG CUSPARSE_MV_ALG_DEFAULT
#define GPUSPARSE_SPMV_CSR_ALG CUSPARSE_MV_ALG_DEFAULT
#define GPUSPARSE_SPMM_COO_ALG CUSPARSE_SPMM_ALG_DEFAULT
#define GPUSPARSE_SPMM_CSR_ALG CUSPARSE_SPMM_ALG_DEFAULT
#endif
#define GPUSPARSE_OPERATION_NON_TRANSPOSE CUSPARSE_OPERATION_NON_TRANSPOSE
#define GPUSPARSE_OPERATION_TRANSPOSE CUSPARSE_OPERATION_TRANSPOSE
#define GPUSPARSE_ORDER_ROW CUSPARSE_ORDER_ROW
#define GPUSPARSE_SPARSETODENSE_ALG_DEFAULT CUSPARSE_SPARSETODENSE_ALG_DEFAULT
#define GPUSPARSE_STATUS_SUCCESS CUSPARSE_STATUS_SUCCESS
#define gpuGetLastError cudaGetLastError
#define gpuGetErrorString cudaGetErrorString
#define gpuMemcpy cudaMemcpy
#define gpuMemcpyAsync cudaMemcpyAsync
#define gpuMemcpyDeviceToDevice cudaMemcpyDeviceToDevice
#define gpuMemcpyHostToDevice cudaMemcpyHostToDevice
#define gpuMemcpyDeviceToHost cudaMemcpyDeviceToHost
#define gpuStreamSynchronize cudaStreamSynchronize
#define gpuSuccess cudaSuccess
#elif defined(JAX_GPU_HIP)
#include "rocm/include/hip/hip_runtime_api.h"
#include "rocm/include/hipblas.h"
#include "rocm/include/hipsolver.h"
#include "rocm/include/hipsparse.h"
#define JAX_GPU_NAMESPACE hip
#define JAX_GPU_PREFIX "hip"
#define JAX_GPU_HAVE_SPARSE 1
#define JAX_GPU_HAVE_FP8 0
typedef hipFloatComplex gpuComplex;
typedef hipDoubleComplex gpuDoubleComplex;
typedef hipblasComplex gpublasComplex;
typedef hipblasDoubleComplex gpublasDoubleComplex;
typedef hipsolverHandle_t gpusolverDnHandle_t;
typedef hipblasFillMode_t gpublasFillMode_t;
typedef hipsolverFillMode_t gpusolverFillMode_t;
typedef hipblasHandle_t gpublasHandle_t;
typedef hipblasStatus_t gpublasStatus_t;
typedef hipDataType gpuDataType;
typedef hipStream_t gpuStream_t;
typedef hipError_t gpuError_t;
typedef void gpuSyevjInfo;
typedef hipsolverSyevjInfo_t gpuSyevjInfo_t;
typedef hipsolverEigMode_t gpusolverEigMode_t;
typedef hipsolverStatus_t gpusolverStatus_t;
typedef hipsparseIndexType_t gpusparseIndexType_t;
typedef hipsparseHandle_t gpusparseHandle_t;
typedef hipsparseOperation_t gpusparseOperation_t;
typedef hipsparseStatus_t gpusparseStatus_t;
typedef hipsparseSpMatDescr_t gpusparseSpMatDescr_t;
typedef hipsparseDnMatDescr_t gpusparseDnMatDescr_t;
typedef hipsparseDnVecDescr_t gpusparseDnVecDescr_t;
#define GPU_C_16F HIP_C_16F
#define GPU_R_16F HIP_R_16F
#define GPU_C_32F HIP_C_32F
#define GPU_R_32F HIP_R_32F
#define GPU_C_64F HIP_C_64F
#define GPU_R_64F HIP_R_64F
#define gpublasCreate hipblasCreate
#define gpublasSetStream hipblasSetStream
#define gpublasSgeqrfBatched hipblasSgeqrfBatched
#define gpublasDgeqrfBatched hipblasDgeqrfBatched
#define gpublasCgeqrfBatched hipblasCgeqrfBatched
#define gpublasZgeqrfBatched hipblasZgeqrfBatched
#define gpublasSgetrfBatched hipblasSgetrfBatched
#define gpublasDgetrfBatched hipblasDgetrfBatched
#define gpublasCgetrfBatched hipblasCgetrfBatched
#define gpublasZgetrfBatched hipblasZgetrfBatched
#define GPUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS
#define gpusolverDnCreate hipsolverCreate
#define gpusolverDnSetStream hipsolverSetStream
#define gpusolverDnCreateSyevjInfo hipsolverCreateSyevjInfo
#define gpusolverDnDestroySyevjInfo hipsolverDestroySyevjInfo
#define gpusolverDnSgeqrf hipsolverSgeqrf
#define gpusolverDnDgeqrf hipsolverDgeqrf
#define gpusolverDnCgeqrf hipsolverCgeqrf
#define gpusolverDnZgeqrf hipsolverZgeqrf
#define gpusolverDnSgeqrf_bufferSize hipsolverSgeqrf_bufferSize
#define gpusolverDnDgeqrf_bufferSize hipsolverDgeqrf_bufferSize
#define gpusolverDnCgeqrf_bufferSize hipsolverCgeqrf_bufferSize
#define gpusolverDnZgeqrf_bufferSize hipsolverZgeqrf_bufferSize
#define gpusolverDnSgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
hipsolverSgetrf(h, m, n, a, lda, work, lwork, ipiv, info)
#define gpusolverDnDgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
hipsolverDgetrf(h, m, n, a, lda, work, lwork, ipiv, info)
#define gpusolverDnCgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
hipsolverCgetrf(h, m, n, a, lda, work, lwork, ipiv, info)
#define gpusolverDnZgetrf(h, m, n, a, lda, work, lwork, ipiv, info) \
hipsolverZgetrf(h, m, n, a, lda, work, lwork, ipiv, info)
#define gpusolverDnSgetrf_bufferSize hipsolverSgetrf_bufferSize
#define gpusolverDnDgetrf_bufferSize hipsolverDgetrf_bufferSize
#define gpusolverDnCgetrf_bufferSize hipsolverCgetrf_bufferSize
#define gpusolverDnZgetrf_bufferSize hipsolverZgetrf_bufferSize
#define gpusolverDnSorgqr hipsolverSorgqr
#define gpusolverDnDorgqr hipsolverDorgqr
#define gpusolverDnCungqr hipsolverCungqr
#define gpusolverDnZungqr hipsolverZungqr
#define gpusolverDnSorgqr_bufferSize hipsolverSorgqr_bufferSize
#define gpusolverDnDorgqr_bufferSize hipsolverDorgqr_bufferSize
#define gpusolverDnCungqr_bufferSize hipsolverCungqr_bufferSize
#define gpusolverDnZungqr_bufferSize hipsolverZungqr_bufferSize
#define gpusolverDnSsyevd hipsolverSsyevd
#define gpusolverDnDsyevd hipsolverDsyevd
#define gpusolverDnCheevd hipsolverCheevd
#define gpusolverDnZheevd hipsolverZheevd
#define gpusolverDnSsyevd_bufferSize hipsolverSsyevd_bufferSize
#define gpusolverDnDsyevd_bufferSize hipsolverDsyevd_bufferSize
#define gpusolverDnCheevd_bufferSize hipsolverCheevd_bufferSize
#define gpusolverDnZheevd_bufferSize hipsolverZheevd_bufferSize
#define gpusolverDnSsyevj hipsolverSsyevj
#define gpusolverDnDsyevj hipsolverDsyevj
#define gpusolverDnCheevj hipsolverCheevj
#define gpusolverDnZheevj hipsolverZheevj
#define gpusolverDnSsyevj_bufferSize hipsolverSsyevj_bufferSize
#define gpusolverDnDsyevj_bufferSize hipsolverDsyevj_bufferSize
#define gpusolverDnCheevj_bufferSize hipsolverCheevj_bufferSize
#define gpusolverDnZheevj_bufferSize hipsolverZheevj_bufferSize
#define gpusolverDnSsyevjBatched hipsolverSsyevjBatched
#define gpusolverDnDsyevjBatched hipsolverDsyevjBatched
#define gpusolverDnCheevjBatched hipsolverCheevjBatched
#define gpusolverDnZheevjBatched hipsolverZheevjBatched
#define gpusolverDnSsyevjBatched_bufferSize hipsolverSsyevjBatched_bufferSize
#define gpusolverDnDsyevjBatched_bufferSize hipsolverDsyevjBatched_bufferSize
#define gpusolverDnCheevjBatched_bufferSize hipsolverCheevjBatched_bufferSize
#define gpusolverDnZheevjBatched_bufferSize hipsolverZheevjBatched_bufferSize
#define gpusolverDnSgesvd hipsolverSgesvd
#define gpusolverDnDgesvd hipsolverDgesvd
#define gpusolverDnCgesvd hipsolverCgesvd
#define gpusolverDnZgesvd hipsolverZgesvd
#define gpusolverDnSgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
hipsolverSgesvd_bufferSize(h, jobu, jobvt, m, n, lwork)
#define gpusolverDnDgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
hipsolverDgesvd_bufferSize(h, jobu, jobvt, m, n, lwork)
#define gpusolverDnCgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
hipsolverCgesvd_bufferSize(h, jobu, jobvt, m, n, lwork)
#define gpusolverDnZgesvd_bufferSize(h, jobu, jobvt, m, n, lwork) \
hipsolverZgesvd_bufferSize(h, jobu, jobvt, m, n, lwork)
#define gpusolverDnSsytrd_bufferSize hipsolverDnSsytrd_bufferSize
#define gpusolverDnDsytrd_bufferSize hipsolverDnDsytrd_bufferSize
#define gpusolverDnChetrd_bufferSize hipsolverDnChetrd_bufferSize
#define gpusolverDnZhetrd_bufferSize hipsolverDnZhetrd_bufferSize
#define gpusolverDnSsytrd hipsolverDnSsytrd
#define gpusolverDnDsytrd hipsolverDnDsytrd
#define gpusolverDnChetrd hipsolverDnChetrd
#define gpusolverDnZhetrd hipsolverDnZhetrd
#define GPUSOLVER_FILL_MODE_LOWER HIPSOLVER_FILL_MODE_LOWER
#define GPUSOLVER_FILL_MODE_UPPER HIPSOLVER_FILL_MODE_UPPER
#define GPUSOLVER_EIG_MODE_VECTOR HIPSOLVER_EIG_MODE_VECTOR
#define GPUSOLVER_STATUS_SUCCESS HIPSOLVER_STATUS_SUCCESS
#define gpusparseCooSetStridedBatch hipsparseCooSetStridedBatch
#define gpusparseCreate hipsparseCreate
#define gpusparseSetStream hipsparseSetStream
#define gpusparseCreateCoo hipsparseCreateCoo
#define gpusparseCreateCsr hipsparseCreateCsr
#define gpusparseCreateDnMat hipsparseCreateDnMat
#define gpusparseCreateDnVec hipsparseCreateDnVec
#define gpusparseDenseToSparse_analysis hipsparseDenseToSparse_analysis
#define gpusparseDenseToSparse_bufferSize hipsparseDenseToSparse_bufferSize
#define gpusparseDenseToSparse_convert hipsparseDenseToSparse_convert
#define gpusparseDestroySpMat hipsparseDestroySpMat
#define gpusparseDestroyDnMat hipsparseDestroyDnMat
#define gpusparseDestroyDnVec hipsparseDestroyDnVec
#define gpusparseDnMatSetStridedBatch hipsparseDnMatSetStridedBatch
#define gpusparseSparseToDense hipsparseSparseToDense
#define gpusparseSparseToDense_bufferSize hipsparseSparseToDense_bufferSize
#define gpusparseSpMM hipsparseSpMM
#define gpusparseSpMM_bufferSize hipsparseSpMM_bufferSize
#define gpusparseSpMV hipsparseSpMV
#define gpusparseSpMV_bufferSize hipsparseSpMV_bufferSize
#define gpusparseSgtsv2 hipsparseSgtsv2
#define gpusparseDgtsv2 hipsparseDgtsv2
#define gpusparseSgtsv2_bufferSizeExt hipsparseSgtsv2_bufferSizeExt
#define gpusparseDgtsv2_bufferSizeExt hipsparseDgtsv2_bufferSizeExt
#define GPUSPARSE_INDEX_16U HIPSPARSE_INDEX_16U
#define GPUSPARSE_INDEX_32I HIPSPARSE_INDEX_32I
#define GPUSPARSE_INDEX_64I HIPSPARSE_INDEX_64I
#define GPUSPARSE_DENSETOSPARSE_ALG_DEFAULT HIPSPARSE_DENSETOSPARSE_ALG_DEFAULT
#define GPUSPARSE_SPMV_COO_ALG HIPSPARSE_MV_ALG_DEFAULT
#define GPUSPARSE_SPMV_CSR_ALG HIPSPARSE_MV_ALG_DEFAULT
#define GPUSPARSE_SPMM_COO_ALG HIPSPARSE_SPMM_ALG_DEFAULT
#define GPUSPARSE_SPMM_CSR_ALG HIPSPARSE_SPMM_ALG_DEFAULT
#define GPUSPARSE_INDEX_BASE_ZERO HIPSPARSE_INDEX_BASE_ZERO
#define GPUSPARSE_OPERATION_NON_TRANSPOSE HIPSPARSE_OPERATION_NON_TRANSPOSE
#define GPUSPARSE_OPERATION_TRANSPOSE HIPSPARSE_OPERATION_TRANSPOSE
#define GPUSPARSE_ORDER_ROW HIPSPARSE_ORDER_ROW
#define GPUSPARSE_SPARSETODENSE_ALG_DEFAULT HIPSPARSE_SPARSETODENSE_ALG_DEFAULT
#define GPUSPARSE_STATUS_SUCCESS HIPSPARSE_STATUS_SUCCESS
#define gpuGetLastError hipGetLastError
#define gpuGetErrorString hipGetErrorString
#define gpuMemcpyAsync hipMemcpyAsync
#define gpuMemcpyDeviceToDevice hipMemcpyDeviceToDevice
#define gpuMemcpyHostToDevice hipMemcpyHostToDevice
#define gpuMemcpyDeviceToHost hipMemcpyDeviceToHost
#define gpuStreamSynchronize hipStreamSynchronize
#define gpuSuccess hipSuccess
#else // defined(GPU vendor)
#error "Either JAX_GPU_CUDA or JAX_GPU_HIP must be defined"
#endif // defined(GPU vendor)
#endif // JAXLIB_GPU_VENDOR_H_
| 20,776 | 45.585202 | 80 |
h
|
hadron
|
hadron-master/src/alpha_s.c
|
#include <R.h>
#include <Rdefines.h>
#include <Rinternals.h>
#include <Rmath.h>
#include <math.h>
SEXP alphas(SEXP mu_, SEXP nl_, SEXP lam0_, SEXP Nc_, SEXP Nf_) {
const double pi = 3.1415926535897932384626433832;
const double Z3 = 1.20206;
double Cf, b0, b1, b2, b3, L2, LL2, als0, als1, als2, als3;
double mu, lam0, *resp, Nc, Nf;
int nl;
SEXP res;
PROTECT(mu_ = AS_NUMERIC(mu_));
PROTECT(nl_ = AS_INTEGER(nl_));
PROTECT(lam0_ = AS_NUMERIC(lam0_));
PROTECT(Nc_ = AS_NUMERIC(Nc_));
PROTECT(Nf_ = AS_NUMERIC(Nf_));
mu = NUMERIC_POINTER(mu_)[0];
nl = INTEGER_POINTER(nl_)[0];
lam0 = NUMERIC_POINTER(lam0_)[0];
Nc = NUMERIC_POINTER(Nc_)[0];
Nf = NUMERIC_POINTER(Nf_)[0];
Cf = (Nc * Nc - 1.) / 2. / Nc;
b0 = 11. / 3. * Nc - 2. / 3. * Nf;
b1 = 34. / 3. * Nc * Nc - 38. / 3. * Nf;
b2 = 2857. / 54. * Nc * Nc * Nc + Cf * Cf * Nf - 205. / 18. * Cf * Nc * Nf -
1415. / 54. * Nc * Nc * Nf + 11. / 9. * Cf * Nf * Nf + 79. / 54. * Nc * Nf * Nf;
b3 = (150653. / 486. - 44. / 9. * Z3) * Nc * Nc * Nc * Nc +
(-39143. / 162. + 68. / 3. * Z3) * Nc * Nc * Nc * Nf +
(7073. / 486. - 328. / 9. * Z3) * Cf * Nc * Nc * Nf +
(-2102. / 27. + 176. / 9. * Z3) * Cf * Cf * Nc * Nf + 23. * Cf * Cf * Cf * Nf +
(3965. / 162. + 56. / 9. * Z3) * Nc * Nc * Nf * Nf +
(338. / 27. - 176. / 9. * Z3) * Cf * Cf * Nf * Nf +
(4288. / 243. + 112. / 9. * Z3) * Cf * Nc * Nf * Nf +
53. / 243. * Nc * Nf * Nf * Nf + 154. / 243. * Cf * Nf * Nf * Nf +
(-10. / 27. + 88. / 9. * Z3) * Nc * Nc * (Nc * Nc + 36.) +
(32. / 27. - 104. / 9. * Z3) * Nc * (Nc * Nc + 6) * Nf +
(-22. / 27. + 16. / 9. * Z3) * (Nc * Nc * Nc * Nc - 6. * Nc * Nc + 18.) /
(Nc * Nc) * Nf * Nf;
b1 = b1 / b0 / 4. / pi;
b2 = b2 / b0 / 16. / pi / pi;
b3 = b3 / b0 / 64. / pi / pi / pi;
L2 = log(mu * mu / lam0 / lam0);
LL2 = log(L2);
als0 = 4. * pi / b0 / L2;
als1 = als0 - als0 * als0 * b1 * LL2;
als2 = als1 + als0 * als0 * als0 * (b1 * b1 * (LL2 * LL2 - LL2 - 1.) + b2);
als3 = als2 + als0 * als0 * als0 * als0 *
(b1 * b1 * b1 *
(-LL2 * LL2 * LL2 + 5. / 2. * LL2 * LL2 + 2 * LL2 - 1. / 2.) -
3. * b1 * b2 * LL2 + b3 / 2.);
PROTECT(res = NEW_NUMERIC(1));
resp = NUMERIC_POINTER(res);
if (nl == 0)
resp[0] = (als0 / (4. * pi));
else if (nl == 1)
resp[0] = (als1 / (4. * pi));
else if (nl == 2)
resp[0] = (als2 / (4. * pi));
else
resp[0] = (als3 / (4. * pi));
UNPROTECT(6);
return (res);
}
double alphas_c(
const double mu, const int nl, const double lam0, const int Nc, const int Nf) {
const double pi = 3.1415926535897932384626433832;
const double Z3 = 1.20206;
double Cf, b0, b1, b2, b3, L2, LL2, als0, als1, als2, als3;
Cf = (Nc * Nc - 1.) / 2. / Nc;
b0 = 11. / 3. * Nc - 2. / 3. * Nf;
b1 = 34. / 3. * Nc * Nc - 38. / 3. * Nf;
b2 = 2857. / 54. * Nc * Nc * Nc + Cf * Cf * Nf - 205. / 18. * Cf * Nc * Nf -
1415. / 54. * Nc * Nc * Nf + 11. / 9. * Cf * Nf * Nf + 79. / 54. * Nc * Nf * Nf;
b3 = (150653. / 486. - 44. / 9. * Z3) * Nc * Nc * Nc * Nc +
(-39143. / 162. + 68. / 3. * Z3) * Nc * Nc * Nc * Nf +
(7073. / 486. - 328. / 9. * Z3) * Cf * Nc * Nc * Nf +
(-2102. / 27. + 176. / 9. * Z3) * Cf * Cf * Nc * Nf + 23. * Cf * Cf * Cf * Nf +
(3965. / 162. + 56. / 9. * Z3) * Nc * Nc * Nf * Nf +
(338. / 27. - 176. / 9. * Z3) * Cf * Cf * Nf * Nf +
(4288. / 243. + 112. / 9. * Z3) * Cf * Nc * Nf * Nf +
53. / 243. * Nc * Nf * Nf * Nf + 154. / 243. * Cf * Nf * Nf * Nf +
(-10. / 27. + 88. / 9. * Z3) * Nc * Nc * (Nc * Nc + 36.) +
(32. / 27. - 104. / 9. * Z3) * Nc * (Nc * Nc + 6) * Nf +
(-22. / 27. + 16. / 9. * Z3) * (Nc * Nc * Nc * Nc - 6. * Nc * Nc + 18.) /
(Nc * Nc) * Nf * Nf;
b1 = b1 / b0 / 4. / pi;
b2 = b2 / b0 / 16. / pi / pi;
b3 = b3 / b0 / 64. / pi / pi / pi;
L2 = log(mu * mu / lam0 / lam0);
LL2 = log(L2);
als0 = 4. * pi / b0 / L2;
als1 = als0 - als0 * als0 * b1 * LL2;
als2 = als1 + als0 * als0 * als0 * (b1 * b1 * (LL2 * LL2 - LL2 - 1.) + b2);
als3 = als2 + als0 * als0 * als0 * als0 *
(b1 * b1 * b1 *
(-LL2 * LL2 * LL2 + 5. / 2. * LL2 * LL2 + 2 * LL2 - 1. / 2.) -
3. * b1 * b2 * LL2 + b3 / 2.);
if (nl == 0)
return (als0 / (4. * pi));
else if (nl == 1)
return (als1 / (4. * pi));
else if (nl == 2)
return (als2 / (4. * pi));
return (als3 / (4. * pi));
}
| 4,561 | 35.790323 | 87 |
c
|
hadron
|
hadron-master/src/cdh.c
|
#include "cdh.h"
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_bessel.h>
#include <math.h>
void my_errhandler(const char *reason, const char *file, int line, int gsl_errno) {
if (gsl_errno != GSL_EUNDRFLW) {
error("ERROR: In GSL the following error occured: %s\nline %d of file %s\n",
gsl_strerror(gsl_errno),
line,
file);
} else {
warning("WARNING: In GSL routines the following error occured: %s in cdh.c\n",
gsl_strerror(gsl_errno));
}
return;
}
double g1(double x) {
double weights[20] = {6., 12., 8., 6., 24., 24., 0., 12., 30., 24.,
24., 8., 24., 48., 0., 6., 48., 36., 24., 24.};
double sex, res = 0.;
int i;
for (i = 0; i < 20; i++) {
sex = x * sqrt((double)(i + 1.));
res += 4. * weights[i] * gsl_sf_bessel_Kn(1, sex) / sex;
}
return (res);
}
int g1array(double *x, double *res, const int n) {
double weights[20] = {6., 12., 8., 6., 24., 24., 0., 12., 30., 24.,
24., 8., 24., 48., 0., 6., 48., 36., 24., 24.};
double ex[20], sex[20];
int i, j;
for (i = 0; i < 20; i++) {
ex[i] = sqrt((double)(i + 1.));
}
for (j = 0; i < n; i++) {
res[j] = 0.;
for (i = 0; i < 20; i++) {
sex[i] = x[j] * ex[i];
res[j] += 4. * weights[i] * gsl_sf_bessel_Kn(1, sex[i]) / sex[i];
}
}
return (0);
}
static R_INLINE void fscdh(double rev,
double aLamb1,
double aLamb2,
double aLamb3,
double aLamb4,
double *aF0,
double a_fm,
int *L,
double *ampiV,
double *afpiV,
const int n,
double *mpiFV,
double *fpiFV,
const int printit,
double *rtilde,
const int incim6) {
const double pi = 3.1415926535897932384626433832;
int i, j;
double N, amrho_phys, z, lambda_pi, tmp;
double gg[4];
double mm[] = {6, 12, 8, 6, 24, 24, 0, 12, 30, 24, 24, 8, 24, 48, 0, 6, 48, 36, 24, 24};
const int mm1 = 20;
double *lb1, *lb2, *lb3, *lb4, *lpi, *xi_P, *mmB0, *mmB2;
double *S4mpi, *S4fpi, *I4mpi, *I2mpi, *I2fpi, *I4fpi, *I6mpi;
gg[0] = 2. - pi / 2.;
gg[1] = pi / 4. - 0.5;
gg[2] = 0.5 - pi / 8.;
gg[3] = 3 * pi / 16. - 0.5;
N = 16 * pi * pi;
amrho_phys = a_fm * 770.0 / 197.3;
lb1 = (double *)Calloc(n, double);
lb2 = (double *)Calloc(n, double);
lb3 = (double *)Calloc(n, double);
lb4 = (double *)Calloc(n, double);
lpi = (double *)Calloc(n, double);
for (i = 0; i < n; i++) {
tmp = 1. / ampiV[i] / ampiV[i];
lb1[i] = log(aLamb1 * aLamb1 * tmp);
lb2[i] = log(aLamb2 * aLamb2 * tmp);
lb3[i] = log(aLamb3 * aLamb3 * tmp);
lb4[i] = log(aLamb4 * aLamb4 * tmp);
lpi[i] = log(ampiV[i] / amrho_phys * ampiV[i] / amrho_phys);
}
mmB0 = (double *)Calloc(n, double);
mmB2 = (double *)Calloc(n, double);
xi_P = (double *)Calloc(n, double);
S4mpi = (double *)Calloc(n, double);
S4fpi = (double *)Calloc(n, double);
I2mpi = (double *)Calloc(n, double);
I4mpi = (double *)Calloc(n, double);
I2fpi = (double *)Calloc(n, double);
I4fpi = (double *)Calloc(n, double);
I6mpi = (double *)Calloc(n, double);
for (i = 0; i < n; i++) {
xi_P[i] = 2. * (ampiV[i] * ampiV[i] / (4 * pi * aF0[i]) / (4 * pi * aF0[i]));
}
for (j = 0; j < n; j++) {
lambda_pi = ampiV[j] * L[j];
for (i = 0; i < mm1; i++) {
z = sqrt(1. + i) * lambda_pi;
mmB0[j] += mm[i] * 2. * gsl_sf_bessel_K1(z) / z;
mmB2[j] += mm[i] * 2. * gsl_sf_bessel_Kn(2, z) / z / z;
}
}
for (i = 0; i < n; i++) {
S4mpi[i] = (13. / 3.) * gg[0] * mmB0[i] -
(1. / 3.) * (40. * gg[0] + 32. * gg[1] + 26. * gg[2]) * mmB2[i];
S4fpi[i] =
(1. / 6.) * (8 * gg[0] - 13. * gg[1]) * mmB0[i] -
(1. / 3.) * (40. * gg[0] - 12. * gg[1] - 8. * gg[2] - 13. * gg[3]) * mmB2[i];
}
for (i = 0; i < n; i++) {
I2mpi[i] = -mmB0[i];
I4mpi[i] = mmB0[i] * (-55. / 18. + 4. * lb1[i] + 8. / 3. * lb2[i] - 5. / 2. * lb3[i] -
2. * lb4[i]) +
mmB2[i] * (112. / 9. - (8. / 3.) * lb1[i] - (32. / 3.) * lb2[i]) +
S4mpi[i];
if (incim6) {
I6mpi[i] =
mmB0[i] * (10049. / 1296. - 13. / 72. * N + 20. / 9. * lb1[i] -
40. / 27. * lb2[i] - 3. / 4. * lb3[i] - 110. / 9. * lb4[i] -
5. / 2. * lb3[i] * lb3[i] - 5. * lb4[i] * lb4[i] +
lb4[i] * (16 * lb1[i] + 32. / 3. * lb2[i] - 11. * lb3[i]) +
lpi[i] * (70. / 9. * lpi[i] + 12 * lb1[i] + 32. / 9. * lb2[i] -
lb3[i] + lb4[i] + 47. / 18.) +
5 * rtilde[0] + 4 * rtilde[1] + 8 * rtilde[2] + 8 * rtilde[3] +
16 * rtilde[4] + 16 * rtilde[5]) +
mmB2[i] *
(3476. / 81. - 77. / 288. * N + 32. / 9. * lb1[i] + 464. / 27. * lb2[i] +
448. / 9. * lb4[i] - 32. / 3. * lb4[i] * (lb1[i] + 4 * lb2[i]) +
lpi[i] * (100. / 9. * lpi[i] + 8. / 3. * lb1[i] + 176. / 9. * lb2[i] -
248. / 9.) -
8 * rtilde[2] - 56 * rtilde[3] - 48 * rtilde[4] + 16 * rtilde[5]);
} else {
I6mpi[i] = 0.;
}
I2fpi[i] = -2 * mmB0[i];
I4fpi[i] = mmB0[i] * (-7. / 9. + 2 * lb1[i] + (4. / 3.) * lb2[i] - 3 * lb4[i]) +
mmB2[i] * (112. / 9. - (8. / 3.) * lb1[i] - (32. / 3.) * lb2[i]) +
S4fpi[i];
}
for (i = 0; i < n; i++) {
/* Rmpi = - (xi_P[i]/2.) * (ampiV[i]/M_P[i]) * (I2mpi[i] + xi_P[i] * I4mpi[i] +
* xi_P^2 * I6mpi[i]); */
mpiFV[i] = ampiV[i] *
(1. - rev * (xi_P[i] / 2.) *
(I2mpi[i] + xi_P[i] * I4mpi[i] + xi_P[i] * xi_P[i] * I6mpi[i]));
/* Rfpi = (xi_P[i]) * (afpiV[i]/F_P[i]) * (I2fpi[i] + xi_P[i] * I4fpi[i] +
* xi_P^2 * I6fpi[i]); */
fpiFV[i] = afpiV[i] * (1. + rev * (xi_P[i]) * (I2fpi[i] + xi_P[i] * I4fpi[i]));
}
if (printit) {
Rprintf("Rmpi ");
for (i = 0; i < n; i++) {
Rprintf("%e ",
-(xi_P[i] / 2.) *
(I2mpi[i] + xi_P[i] * I4mpi[i] + xi_P[i] * xi_P[i] * I6mpi[i]));
}
Rprintf("\nRfpi ");
for (i = 0; i < n; i++) {
Rprintf("%e ", (xi_P[i]) * (I2fpi[i] + xi_P[i] * I4fpi[i]));
}
Rprintf("\n");
}
Free(lb1);
Free(lb2);
Free(lb3);
Free(lb4);
Free(lpi);
Free(xi_P);
Free(mmB0);
Free(mmB2);
Free(S4mpi);
Free(S4fpi);
Free(I4mpi);
Free(I2mpi);
Free(I2fpi);
Free(I4fpi);
Free(I6mpi);
return;
}
static R_INLINE void fscdhnew(double rev,
double aLamb1,
double aLamb2,
double aLamb3,
double aLamb4,
double aF0,
int *L,
double *ampiV,
double *afpiV,
double *a2B0mu,
const int n,
double *mpiFV,
double *fpiFV,
const int printit) {
const double pi = 3.1415926535897932384626433832;
int i, j;
double N, z, tmp;
double gg[4];
double mm[] = {6, 12, 8, 6, 24, 24, 0, 12, 30, 24, 24, 8, 24, 48, 0, 6, 48, 36, 24, 24};
const int mm1 = 20;
double *lb1, *lb2, *lb3, *lb4, *DeltaM, *DeltaF, *xi_P, *mmB0, *mmB1, *mmB2;
double *S4mpi, *S4fpi, *I4mpi, *I2mpi, *I2fpi, *I4fpi;
gg[0] = 2. - pi / 2.;
gg[1] = pi / 4. - 0.5;
gg[2] = 0.5 - pi / 8.;
gg[3] = 3 * pi / 16. - 0.5;
N = 16 * pi * pi;
lb1 = (double *)Calloc(n, double);
lb2 = (double *)Calloc(n, double);
lb3 = (double *)Calloc(n, double);
lb4 = (double *)Calloc(n, double);
for (i = 0; i < n; i++) {
tmp = 1. / a2B0mu[i];
lb1[i] = log(aLamb1 * aLamb1 * tmp);
lb2[i] = log(aLamb2 * aLamb2 * tmp);
lb3[i] = log(aLamb3 * aLamb3 * tmp);
lb4[i] = log(aLamb4 * aLamb4 * tmp);
}
DeltaM = (double *)Calloc(n, double);
DeltaF = (double *)Calloc(n, double);
mmB0 = (double *)Calloc(n, double);
mmB1 = (double *)Calloc(n, double);
mmB2 = (double *)Calloc(n, double);
xi_P = (double *)Calloc(n, double);
S4mpi = (double *)Calloc(n, double);
S4fpi = (double *)Calloc(n, double);
I2mpi = (double *)Calloc(n, double);
I4mpi = (double *)Calloc(n, double);
I2fpi = (double *)Calloc(n, double);
I4fpi = (double *)Calloc(n, double);
for (i = 0; i < n; i++) {
xi_P[i] = 2. * a2B0mu[i] / (4 * pi * aF0) / (4 * pi * aF0);
}
for (j = 0; j < n; j++) {
for (i = 0; i < mm1; i++) {
z = sqrt(1. + i) * sqrt(a2B0mu[j]) * L[j];
mmB0[j] += mm[i] * 2. * gsl_sf_bessel_K0(z);
mmB1[j] += mm[i] * 2. * gsl_sf_bessel_K1(z) / z;
mmB2[j] += mm[i] * 2. * gsl_sf_bessel_Kn(2, z) / z / z;
}
DeltaM[j] = -lb3[j] / (2. * N);
DeltaF[j] = 2. * lb4[j] / N;
}
for (i = 0; i < n; i++) {
S4mpi[i] = (13. / 3.) * gg[0] * mmB1[i] -
(1. / 3.) * (40. * gg[0] + 32. * gg[1] + 26. * gg[2]) * mmB2[i];
S4fpi[i] =
(1. / 6.) * (8 * gg[0] - 13. * gg[1]) * mmB1[i] -
(1. / 3.) * (40. * gg[0] - 12. * gg[1] - 8. * gg[2] - 13. * gg[3]) * mmB2[i];
}
for (i = 0; i < n; i++) {
I2mpi[i] = -mmB1[i];
I4mpi[i] = mmB1[i] * (-55. / 18. + 4. * lb1[i] + 8. / 3. * lb2[i] - 5. / 2. * lb3[i] -
2. * lb4[i]) +
mmB2[i] * (112. / 9. - (8. / 3.) * lb1[i] - (32. / 3.) * lb2[i]) +
S4mpi[i] + N / 2. * DeltaM[i] * mmB0[i] + N * DeltaF[i] * mmB1[i];
}
for (i = 0; i < n; i++) {
I2fpi[i] = -2 * mmB1[i];
I4fpi[i] = mmB1[i] * (-7. / 9. + 2. * lb1[i] + (4. / 3.) * lb2[i] - 3. * lb4[i]) +
mmB2[i] * (112. / 9. - (8. / 3.) * lb1[i] - (32. / 3.) * lb2[i]) +
S4fpi[i] + N * DeltaM[i] * mmB0[i] + 2 * N * DeltaF[i] * mmB1[i];
}
for (i = 0; i < n; i++) {
mpiFV[i] = ampiV[i] * (1 + rev * (-(xi_P[i] / 2) * (I2mpi[i] + xi_P[i] * I4mpi[i])));
fpiFV[i] = afpiV[i] * (1 + rev * ((xi_P[i]) * (I2fpi[i] + xi_P[i] * I4fpi[i])));
}
if (printit) {
Rprintf("Rmpi ");
for (i = 0; i < n; i++) {
Rprintf("%f ", -(xi_P[i] / 2.) * (I2mpi[i] + xi_P[i] * I4mpi[i]));
}
Rprintf("\nRfpi ");
for (i = 0; i < n; i++) {
Rprintf("%f ", (xi_P[i]) * (I2fpi[i] + xi_P[i] * I4fpi[i]));
}
Rprintf("\n");
}
Free(lb1);
Free(lb2);
Free(lb3);
Free(lb4);
Free(DeltaM);
Free(DeltaF);
Free(xi_P);
Free(mmB0);
Free(mmB1);
Free(S4mpi);
Free(S4fpi);
Free(I4mpi);
Free(I2mpi);
Free(I2fpi);
Free(I4fpi);
Free(mmB2);
return;
}
SEXP cdh_c(SEXP rev,
SEXP L1,
SEXP L2,
SEXP L3,
SEXP L4,
SEXP F0,
SEXP a,
SEXP L,
SEXP mpi,
SEXP fpi,
SEXP printit,
SEXP rtilde,
SEXP incim6) {
double *revp, *L1p, *L2p, *L3p, *L4p, *F0p, *ap, *mpip, *fpip, *resp, *rtildep;
int *Lp, *printitp, *incim6p;
SEXP res;
int N;
PROTECT(rev = AS_NUMERIC(rev));
PROTECT(L1 = AS_NUMERIC(L1));
PROTECT(L2 = AS_NUMERIC(L2));
PROTECT(L3 = AS_NUMERIC(L3));
PROTECT(L4 = AS_NUMERIC(L4));
PROTECT(F0 = AS_NUMERIC(F0));
PROTECT(a = AS_NUMERIC(a));
PROTECT(L = AS_INTEGER(L));
PROTECT(mpi = AS_NUMERIC(mpi));
PROTECT(fpi = AS_NUMERIC(fpi));
PROTECT(printit = AS_INTEGER(printit));
PROTECT(rtilde = AS_NUMERIC(rtilde));
PROTECT(incim6 = AS_INTEGER(incim6));
revp = NUMERIC_POINTER(rev);
L1p = NUMERIC_POINTER(L1);
L2p = NUMERIC_POINTER(L2);
L3p = NUMERIC_POINTER(L3);
L4p = NUMERIC_POINTER(L4);
F0p = NUMERIC_POINTER(F0);
ap = NUMERIC_POINTER(a);
Lp = INTEGER_POINTER(L);
mpip = NUMERIC_POINTER(mpi);
fpip = NUMERIC_POINTER(fpi);
printitp = INTEGER_POINTER(printit);
rtildep = NUMERIC_POINTER(rtilde);
incim6p = INTEGER_POINTER(incim6);
N = LENGTH(mpi);
PROTECT(res = NEW_NUMERIC(2 * N));
resp = NUMERIC_POINTER(res);
gsl_error_handler_t *old_handler;
old_handler = gsl_set_error_handler(&my_errhandler);
fscdh(revp[0],
L1p[0],
L2p[0],
L3p[0],
L4p[0],
F0p,
ap[0],
Lp,
mpip,
fpip,
N,
resp,
&resp[N],
printitp[0],
rtildep,
incim6p[0]);
gsl_set_error_handler(old_handler);
UNPROTECT(14);
return (res);
}
SEXP cdhnew_c(SEXP rev,
SEXP L1,
SEXP L2,
SEXP L3,
SEXP L4,
SEXP F0,
SEXP a2B0mu,
SEXP L,
SEXP mpi,
SEXP fpi,
SEXP printit) {
double *revp, *L1p, *L2p, *L3p, *L4p, *F0p, *mpip, *fpip, *resp, *a2B0mup;
int *Lp, *printitp;
SEXP res;
int N;
PROTECT(rev = AS_NUMERIC(rev));
PROTECT(L1 = AS_NUMERIC(L1));
PROTECT(L2 = AS_NUMERIC(L2));
PROTECT(L3 = AS_NUMERIC(L3));
PROTECT(L4 = AS_NUMERIC(L4));
PROTECT(F0 = AS_NUMERIC(F0));
PROTECT(L = AS_INTEGER(L));
PROTECT(mpi = AS_NUMERIC(mpi));
PROTECT(fpi = AS_NUMERIC(fpi));
PROTECT(a2B0mu = AS_NUMERIC(a2B0mu));
PROTECT(printit = AS_INTEGER(printit));
revp = NUMERIC_POINTER(rev);
L1p = NUMERIC_POINTER(L1);
L2p = NUMERIC_POINTER(L2);
L3p = NUMERIC_POINTER(L3);
L4p = NUMERIC_POINTER(L4);
F0p = NUMERIC_POINTER(F0);
Lp = INTEGER_POINTER(L);
mpip = NUMERIC_POINTER(mpi);
fpip = NUMERIC_POINTER(fpi);
a2B0mup = NUMERIC_POINTER(a2B0mu);
printitp = INTEGER_POINTER(printit);
N = LENGTH(mpi);
PROTECT(res = NEW_NUMERIC(2 * N));
resp = NUMERIC_POINTER(res);
gsl_error_handler_t *old_handler;
old_handler = gsl_set_error_handler(&my_errhandler);
fscdhnew(revp[0],
L1p[0],
L2p[0],
L3p[0],
L4p[0],
F0p[0],
Lp,
mpip,
fpip,
a2B0mup,
N,
resp,
&resp[N],
printitp[0]);
gsl_set_error_handler(old_handler);
UNPROTECT(12);
return (res);
}
| 14,317 | 29.659529 | 90 |
c
|
hadron
|
hadron-master/src/cdh.h
|
#pragma once
#include <R.h>
#include <Rdefines.h>
#include <Rinternals.h>
#include <Rmath.h>
double g1(double x);
int g1array(double *x, double *res, const int n);
static R_INLINE void fscdh(double rev,
double aLamb1,
double aLamb2,
double aLamb3,
double aLamb4,
double *aF0,
double a_fm,
int *L,
double *ampiV,
double *afpiV,
const int n,
double *mpiFV,
double *fpiFV,
const int printit,
double *rtilde,
const int incim6);
static R_INLINE void fscdhnew(double rev,
double aLamb1,
double aLamb2,
double aLamb3,
double aLamb4,
double aF0,
int *L,
double *ampiV,
double *afpiV,
double *a2B0mu,
const int n,
double *mpiFV,
double *fpiFV,
const int printit);
| 1,453 | 34.463415 | 49 |
h
|
hadron
|
hadron-master/src/inv_cosh.c
|
#include <R.h>
#include <Rinternals.h>
#include <math.h>
SEXP invcosh(SEXP ratio, SEXP timeextent, SEXP t, SEXP eps, SEXP maxiter) {
const double rat = asReal(ratio), epsilon = asReal(eps);
const int dt0 = asInteger(timeextent) - 2 * asInteger(t), dt1 = dt0 + 2;
const int n = asInteger(maxiter);
double newmass = log(rat), mass = 0, r;
int i;
for (i = 0; i < n && fabs(mass - newmass) >= epsilon * mass; i++) {
mass = newmass;
r = (1 + exp(-mass * dt0)) / (1 + exp(-mass * dt1));
newmass = log(rat * r);
}
return ScalarReal(newmass);
}
| 569 | 26.142857 | 75 |
c
|
hadron
|
hadron-master/src/tmcdh.c
|
#include <R.h>
#include <Rdefines.h>
#include <Rinternals.h>
#include <Rmath.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf_bessel.h>
#include <complex.h>
#include <math.h>
const double N = 16. * M_PI * M_PI;
const double fmGeV = 0.1973269631;
double w(const double x, const double lambda) {
return (exp(-sqrt(1. + x * x) * lambda));
}
double complex Jb(const double complex x) {
double complex sigma;
if (cabs(x) < 1.e-10) {
sigma = csqrt(1. - 4. / x);
return ((sigma * clog((sigma - 1.) / (sigma + 1.)) + 2.) / N);
}
return (0. * I);
}
double complex Jb1(const double complex x) {
double complex sigma;
if (cabs(x) < 1.e-10) {
sigma = csqrt(1. - 4. / x);
return ((2. / x / sigma * clog((sigma - 1.) / (sigma + 1.)) - 1.) / N / x);
}
return (1. / 6. / N + 0. * I);
}
typedef struct {
int n;
int k;
double lambda;
} pars;
double x1(double x, void *params_) {
double complex K;
double complex z = 2 * (1. + I * x);
pars *params = (pars *)params_;
if (params->n == 0) {
K = Jb(z);
} else {
K = Jb1(z);
}
if (params->k % 2 == 0) {
return (w(x, params->lambda) * pow(x, params->k) * cimag(K));
}
return (w(x, params->lambda) * pow(x, params->k) * creal(K));
}
void calc_R_int(double *R[], const double lambda) {
double result, error;
int i, j;
gsl_function F;
gsl_integration_workspace *w;
pars params;
const int intervals = 1000000;
w = gsl_integration_workspace_alloc(intervals);
F.function = &x1;
F.params = (void *)¶ms;
params.lambda = lambda;
for (i = 0; i < 2; i++) {
params.n = i;
for (j = 0; j < 3; j++) {
params.k = j;
gsl_integration_qagi(&F, 0., 1.e-6, intervals, w, &result, &error);
R[i][j] = N * result;
}
}
gsl_integration_workspace_free(w);
}
| 1,837 | 20.372093 | 79 |
c
|
null |
CIF-HieraDist-main/fairseq/clib/libnat_cuda/edit_dist.h
|
/**
* Copyright 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <torch/extension.h>
torch::Tensor LevenshteinDistanceCuda(
torch::Tensor source,
torch::Tensor target,
torch::Tensor source_length,
torch::Tensor target_length);
torch::Tensor GenerateDeletionLabelCuda(
torch::Tensor source,
torch::Tensor operations);
std::pair<torch::Tensor, torch::Tensor> GenerateInsertionLabelCuda(
torch::Tensor source,
torch::Tensor operations);
| 627 | 23.153846 | 67 |
h
|
flexi
|
flexi-master/posti/visu/pluginTypes_visu.h
|
/*
!=================================================================================================================================
! Copyright (c) 2016 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
*/
#ifndef PLUGIN_DUMMY_H
#define PLUGIN_DUMMY_H
struct DoubleARRAY{
int len;
int dim;
double* data;
};
struct IntARRAY{
int len;
int dim;
int* data;
};
struct CharARRAY{
int len;
int dim;
char* data;
};
#endif /* PLUGIN_DUMMY_H */
| 1,402 | 34.974359 | 130 |
h
|
flexi
|
flexi-master/posti/visu/paraviewReader/Reader/visuReader.h
|
/*
!=================================================================================================================================
! Copyright (c) 2016 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
*/
#ifndef VISUREADER_H
#define VISUREADER_H
#include <vtkUnstructuredGridAlgorithm.h>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <vtkMPI.h>
#include <vtkMPICommunicator.h>
#include <vtkMPIController.h>
#include <vtkDataArraySelection.h>
#include <vtkCallbackCommand.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <../../pluginTypes_visu.h>
#include <vtkIOParallelModule.h> // For export macro
#include <vtkMultiBlockDataSetAlgorithm.h>
// MPI
class vtkMultiProcessController;
// MPI
class VTKIOPARALLEL_EXPORT visuReader : public vtkMultiBlockDataSetAlgorithm
{
public:
vtkTypeMacro(visuReader,vtkMultiBlockDataSetAlgorithm);
static visuReader *New();
// macros to set GUI changes to variables
// gui interaction
vtkSetStringMacro(FileName);
vtkSetStringMacro(MeshFileOverwrite);
vtkSetMacro(NVisu,int);
vtkSetMacro(NCalc,int);
vtkSetMacro(HighOrder,int);
vtkSetStringMacro(NodeTypeVisu);
vtkSetMacro(Avg2d,int);
vtkSetMacro(DGonly,int);
// Adds names of files to be read. The files are read in the order they are added.
void AddFileName(const char* fname);
// Remove all file names.
void RemoveAllFileNames();
vtkSetStringMacro(ParameterFileOverwrite);
int GetNumberOfVarArrays();
const char* GetVarArrayName(int index);
int GetVarArrayStatus(const char* name);
void SetVarArrayStatus(const char* name, int status);
void DisableAllVarArrays();
void EnableAllVarArrays();
int GetNumberOfBCArrays();
const char* GetBCArrayName(int index);
int GetBCArrayStatus(const char* name);
void SetBCArrayStatus(const char* name, int status);
void DisableAllBCArrays();
void EnableAllBCArrays();
// MPI
void SetController(vtkMultiProcessController *);
vtkGetObjectMacro(Controller, vtkMultiProcessController);
// MPI
void ConvertToFortran(char* fstring, const char* cstring);
// struct to exchange arrays between fortran and C
struct DoubleARRAY coords_DG;
struct DoubleARRAY values_DG;
struct IntARRAY nodeids_DG;
struct DoubleARRAY coords_FV;
struct DoubleARRAY values_FV;
struct IntARRAY nodeids_FV;
struct CharARRAY varnames;
struct DoubleARRAY coordsSurf_DG;
struct DoubleARRAY valuesSurf_DG;
struct IntARRAY nodeidsSurf_DG;
struct DoubleARRAY coordsSurf_FV;
struct DoubleARRAY valuesSurf_FV;
struct IntARRAY nodeidsSurf_FV;
struct CharARRAY varnamesSurf;
int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
void InsertData(vtkMultiBlockDataSet* mb, int blockno, struct DoubleARRAY* coords,
struct DoubleARRAY* values, struct IntARRAY* nodeids, struct CharARRAY* varnames);
vtkDataArraySelection* VarDataArraySelection;
vtkDataArraySelection* BCDataArraySelection;
// The observer to modify this object when the array selections are modified.
vtkCallbackCommand* SelectionObserver;
// Callback registered with the SelectionObserver.
static void SelectionModifiedCallback(vtkObject* caller, unsigned long eid,
void* clientdata, void* calldata);
char* FileName;
int NVisu;
int NCalc;
int HighOrder;
char* NodeTypeVisu;
int Avg2d;
int DGonly;
char* ParameterFileOverwrite;
char* MeshFileOverwrite;
std::vector<bool> VarNames_selected;
std::vector<bool> BCNames_selected;
int NumProcesses;
int ProcessId;
// all loaded filenames, timesteps (multiple for timeseries)
std::vector<std::string> FileNames;
std::vector<double> Timesteps;
int FindClosestTimeStep(double requestedTimeValue);
//void SetNodeTypeVisu(const char* nodetypevisu);
vtkStringArray* GetNodeTypeVisuList();
protected:
visuReader();
~visuReader();
virtual int FillOutputPortInformation(int port, vtkInformation* info);
private:
// MPI
vtkMultiProcessController *Controller;
MPI_Comm mpiComm;
};
#endif //VISUREADER_H
| 5,483 | 33.062112 | 130 |
h
|
flexi
|
flexi-master/src/equations/linearscalaradvection/eos.h
|
!=================================================================================================================================
! Copyright (c) 2010-2016 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
! Define variables for normal and extended state vector
! Normal U(1:1) with conservative variables
! Extended U(1:2) with conservative and primitive variables
#define CONS 1:PP_nVar /* all cons variables */
#define PRIM 1:PP_nVarPrim /* all prim variables */
#define PP_2Var PP_nVar+PP_nVarPrim
! Lifting
#define PP_nVarLifting 1
#define LIFT_VARS (/1/)
#define PRIM_LIFT (/1/)
| 1,594 | 60.346154 | 130 |
h
|
flexi
|
flexi-master/src/output/read_userblock.c
|
#include <string.h>
#include <stdio.h>
extern char userblock_start;
extern char userblock_end;
extern char userblock_size;
long get_userblock_size_(void)
{
//return (unsigned long)(&userblock_size);
// Fixes mysterious bug occurring on some systems potentially due to the new GCC 7.3
// where userblock_size is wrong though the symbol is correctly defined.
// Since userblock_size = userblock_end - userblock_start , we just compute it on the fly.
return (unsigned long)(&userblock_end-&userblock_start);
}
void insert_userblock(char* filename, char* inifilename)
{
FILE* fp = fopen(filename, "w");
rewind(fp);
fprintf(fp, "{[( START USERBLOCK )]}\n");
// ini file
fprintf(fp, "{[( INIFILE )]}\n");
FILE* fini = fopen(inifilename, "rb");
int c;
do {
c = fgetc (fini);
if (c != EOF) fputc((char)c, fp);
} while (c != EOF);
fclose(fini);
// compressed data ( as tar.xz )
fprintf(fp, "{[( COMPRESSED )]}\n");
fprintf(fp, "userblock.txt\n"); // filename
fprintf(fp, "%ld\n", get_userblock_size_()); // filesize
char* p = &userblock_start;
while ( p != &userblock_end ) fputc(*p++, fp);
fprintf(fp, "\n");
fprintf(fp, "{[( END USERBLOCK )]}\n");
fclose(fp);
}
void copy_userblock(char* outfilename, char* infilename)
{
FILE* fout = fopen(outfilename,"rb+");
FILE* fin = fopen(infilename, "r");
rewind(fout);
int c;
do {
c = fgetc (fin);
if (c != EOF) fputc((char) c, fout);
} while (c != EOF);
fclose(fin);
fclose(fout);
}
| 1,552 | 26.245614 | 93 |
c
|
null |
EDIPIC-2D-main/src/WELL19937a_new.c
|
/* ***************************************************************************** */
/* Copyright: Francois Panneton and Pierre L'Ecuyer, University of Montreal */
/* Makoto Matsumoto, Hiroshima University */
/* Notice: This code can be used freely for personal, academic, */
/* or non-commercial purposes. For commercial purposes, */
/* please contact P. L'Ecuyer at: [email protected] */
/* A modified "maximally equidistributed" implementation */
/* by Shin Harase, Hiroshima University. */
/* ***************************************************************************** */
#include <stdio.h>
#define W 32
#define R 624
#define DISCARD 31
#define MASKU (0xffffffffU>>(W-DISCARD))
#define MASKL (~MASKU)
#define M1 70
#define M2 179
#define M3 449
#define MAT0POS(t,v) (v^(v>>t))
#define MAT0NEG(t,v) (v^(v<<(-(t))))
#define MAT1(v) v
#define MAT3POS(t,v) (v>>t)
#define V0 STATE[state_i]
#define VM1Over STATE[state_i+M1-R]
#define VM1 STATE[state_i+M1]
#define VM2Over STATE[state_i+M2-R]
#define VM2 STATE[state_i+M2]
#define VM3Over STATE[state_i+M3-R]
#define VM3 STATE[state_i+M3]
#define VRm1 STATE[state_i-1]
#define VRm1Under STATE[state_i+R-1]
#define VRm2 STATE[state_i-2]
#define VRm2Under STATE[state_i+R-2]
#define newV0 STATE[state_i-1]
#define newV0Under STATE[state_i-1+R]
#define newV1 STATE[state_i]
#define newVRm1 STATE[state_i-2]
#define newVRm1Under STATE[state_i-2+R]
#define newVM2Over STATE[state_i+M2-R+1]
#define newVM2 STATE[state_i+M2+1]
/*tempering paramater*/
#define BITMASK 0x41180000
/* #define FACT 2.32830643653869628906e-10 */
#define FACT 0x1.00000001P-32
static int state_i = 0;
static int func_num = 1;
static unsigned int STATE[R];
static unsigned int z0, z1, z2, y;
static double case_1 (void);
static double case_2 (void);
static double case_3 (void);
static double case_4 (void);
static double case_5 (void);
static double case_6 (void);
double (*WELLRNG19937)(void);
void set_state (unsigned int *init_state, unsigned int *state_ind, unsigned int *func){
int j;
state_i = (int) *state_ind;
switch(*func) {
case 1:
WELLRNG19937=case_1;
func_num=1;
break;
case 2:
WELLRNG19937=case_2;
func_num=2;
break;
case 3:
WELLRNG19937=case_3;
func_num=3;
break;
case 4:
WELLRNG19937=case_4;
func_num=4;
break;
case 5:
WELLRNG19937=case_5;
func_num=5;
break;
case 6:
WELLRNG19937=case_6;
func_num=6;
break;
default:
/* in case for inconsistent input */
WELLRNG19937=case_1;
func_num=1;
break;
}
for (j = 0; j < R; j++)
STATE[j] = init_state[j];
}
void get_state(unsigned int *init_state, unsigned int *state_ind, unsigned int *func)
{
int j;
*state_ind=state_i;
*func=func_num;
for (j = 0; j<R; j++)
init_state[j]=STATE[j];
}
static double case_1 (void){
// state_i == 0
z0 = (VRm1Under & MASKL) | (VRm2Under & MASKU);
z1 = MAT0NEG (-25, V0) ^ MAT0POS (27, VM1);
z2 = MAT3POS (9, VM2) ^ MAT0POS (1, VM3);
newV1 = z1 ^ z2;
newV0Under = MAT1 (z0) ^ MAT0NEG (-9, z1) ^ MAT0NEG (-21, z2) ^ MAT0POS (21, newV1);
state_i = R - 1;
WELLRNG19937 = case_3;
func_num=3;
y = (STATE[state_i] ^ (newVM2Over & BITMASK));
return ((double) y * FACT);
}
static double case_2 (void){
// state_i == 1
z0 = (VRm1 & MASKL) | (VRm2Under & MASKU);
z1 = MAT0NEG (-25, V0) ^ MAT0POS (27, VM1);
z2 = MAT3POS (9, VM2) ^ MAT0POS (1, VM3);
newV1 = z1 ^ z2;
newV0 = MAT1 (z0) ^ MAT0NEG (-9, z1) ^ MAT0NEG (-21, z2) ^ MAT0POS (21, newV1);
state_i = 0;
WELLRNG19937 = case_1;
func_num=1;
y = (STATE[state_i] ^ (newVM2 & BITMASK));
return ((double) y * FACT);
}
static double case_3 (void){
// state_i+M1 >= R
z0 = (VRm1 & MASKL) | (VRm2 & MASKU);
z1 = MAT0NEG (-25, V0) ^ MAT0POS (27, VM1Over);
z2 = MAT3POS (9, VM2Over) ^ MAT0POS (1, VM3Over);
newV1 = z1 ^ z2;
newV0 = MAT1 (z0) ^ MAT0NEG (-9, z1) ^ MAT0NEG (-21, z2) ^ MAT0POS (21, newV1);
state_i--;
if (state_i + M1 < R) {
WELLRNG19937 = case_5;
func_num=5;
}
y = (STATE[state_i] ^ (newVM2Over & BITMASK));
return ((double) y * FACT);
}
static double case_4 (void){
// state_i+M3 >= R
z0 = (VRm1 & MASKL) | (VRm2 & MASKU);
z1 = MAT0NEG (-25, V0) ^ MAT0POS (27, VM1);
z2 = MAT3POS (9, VM2) ^ MAT0POS (1, VM3Over);
newV1 = z1 ^ z2;
newV0 = MAT1 (z0) ^ MAT0NEG (-9, z1) ^ MAT0NEG (-21, z2) ^ MAT0POS (21, newV1);
state_i--;
if (state_i + M3 < R) {
WELLRNG19937 = case_6;
func_num=6;
}
y = (STATE[state_i] ^ (newVM2 & BITMASK));
return ((double) y * FACT);
}
static double case_5 (void){
// state_i+M2 >= R
z0 = (VRm1 & MASKL) | (VRm2 & MASKU);
z1 = MAT0NEG (-25, V0) ^ MAT0POS (27, VM1);
z2 = MAT3POS (9, VM2Over) ^ MAT0POS (1, VM3Over);
newV1 = z1 ^ z2;
newV0 = MAT1 (z0) ^ MAT0NEG (-9, z1) ^ MAT0NEG (-21, z2) ^ MAT0POS (21, newV1);
state_i--;
if (state_i + M2 < R) {
WELLRNG19937 = case_4;
func_num=4;
}
y = (STATE[state_i] ^ (newVM2Over & BITMASK));
return ((double) y * FACT);
}
static double case_6 (void){
// 2 <= state_i <= (R - M3 - 1)
z0 = (VRm1 & MASKL) | (VRm2 & MASKU);
z1 = MAT0NEG (-25, V0) ^ MAT0POS (27, VM1);
z2 = MAT3POS (9, VM2) ^ MAT0POS (1, VM3);
newV1 = z1 ^ z2;
newV0 = MAT1 (z0) ^ MAT0NEG (-9, z1) ^ MAT0NEG (-21, z2) ^ MAT0POS (21, newV1);
state_i--;
if (state_i == 1) {
WELLRNG19937 = case_2;
func_num=2;
}
y = (STATE[state_i] ^ (newVM2 & BITMASK));
return ((double) y * FACT);
}
| 5,992 | 28.234146 | 87 |
c
|
flexi-particle
|
flexi-particle-master/posti/visu/pluginTypes_visu.h
|
/*
!=================================================================================================================================
! Copyright (c) 2016 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
*/
#ifndef PLUGIN_DUMMY_H
#define PLUGIN_DUMMY_H
struct DoubleARRAY{
int len;
int dim;
double* data;
};
struct IntARRAY{
int len;
int dim;
int* data;
};
struct CharARRAY{
int len;
int dim;
char* data;
};
#endif /* PLUGIN_DUMMY_H */
| 1,402 | 34.974359 | 130 |
h
|
flexi-particle
|
flexi-particle-master/posti/visu/paraviewReader/Reader/visuReader.h
|
/*
!=================================================================================================================================
! Copyright (c) 2016 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
*/
#ifndef VISUREADER_H
#define VISUREADER_H
#include <vtkUnstructuredGridAlgorithm.h>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <vtkMPI.h>
#include <vtkMPICommunicator.h>
#include <vtkMPIController.h>
#include <vtkDataArraySelection.h>
#include <vtkCallbackCommand.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <../../pluginTypes_visu.h>
#include <vtkIOParallelModule.h> // For export macro
#include <vtkMultiBlockDataSetAlgorithm.h>
// MPI
class vtkMultiProcessController;
// MPI
class VTKIOPARALLEL_EXPORT visuReader : public vtkMultiBlockDataSetAlgorithm
{
public:
vtkTypeMacro(visuReader,vtkMultiBlockDataSetAlgorithm);
static visuReader *New();
// macros to set GUI changes to variables
// gui interaction
vtkSetStringMacro(FileName);
vtkSetStringMacro(MeshFileOverwrite);
vtkSetMacro(NVisu,int);
vtkSetMacro(NCalc,int);
vtkSetMacro(UseD3,int);
vtkSetMacro(HighOrder,int);
vtkSetMacro(UseCurveds,int);
vtkSetStringMacro(NodeTypeVisu);
vtkSetMacro(Avg2d,int);
vtkSetMacro(DGonly,int);
// Adds names of files to be read. The files are read in the order they are added.
void AddFileName(const char* fname);
// Remove all file names.
void RemoveAllFileNames();
vtkSetStringMacro(ParameterFileOverwrite);
int GetNumberOfVarArrays();
const char* GetVarArrayName(int index);
int GetVarArrayStatus(const char* name);
void SetVarArrayStatus(const char* name, int status);
void DisableAllVarArrays();
void EnableAllVarArrays();
int GetNumberOfBCArrays();
const char* GetBCArrayName(int index);
int GetBCArrayStatus(const char* name);
void SetBCArrayStatus(const char* name, int status);
void DisableAllBCArrays();
void EnableAllBCArrays();
int GetNumberOfVarParticleArrays();
const char* GetVarParticleArrayName(int index);
int GetVarParticleArrayStatus(const char* name);
void SetVarParticleArrayStatus(const char* name, int status);
void DisableAllVarParticleArrays();
void EnableAllVarParticleArrays();
// MPI
void SetController(vtkMultiProcessController *);
vtkGetObjectMacro(Controller, vtkMultiProcessController);
// MPI
void ConvertToFortran(char* fstring, const char* cstring);
// struct to exchange arrays between fortran and C
struct DoubleARRAY coords_DG;
struct DoubleARRAY values_DG;
struct IntARRAY nodeids_DG;
struct IntARRAY globalnodeids_DG;
struct IntARRAY globalcellids_DG;
struct DoubleARRAY coords_FV;
struct DoubleARRAY values_FV;
struct IntARRAY nodeids_FV;
struct IntARRAY globalnodeids_FV;
struct IntARRAY globalcellids_FV;
struct CharARRAY varnames;
struct DoubleARRAY coordsSurf_DG;
struct DoubleARRAY valuesSurf_DG;
struct IntARRAY nodeidsSurf_DG;
struct IntARRAY globalnodeidsSurf_DG;
struct IntARRAY globalcellidsSurf_DG;
struct DoubleARRAY coordsSurf_FV;
struct DoubleARRAY valuesSurf_FV;
struct IntARRAY nodeidsSurf_FV;
struct IntARRAY globalnodeidsSurf_FV;
struct IntARRAY globalcellidsSurf_FV;
struct CharARRAY varnamesSurf;
struct DoubleARRAY coords_Part;
struct DoubleARRAY values_Part;
struct IntARRAY nodeids_Part;
struct CharARRAY varnames_Part;
struct IntARRAY components_Part;
struct DoubleARRAY coords_Impact;
struct DoubleARRAY values_Impact;
struct IntARRAY nodeids_Impact;
struct CharARRAY varnames_Impact;
struct IntARRAY components_Impact;
int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
void InsertData (vtkMultiBlockDataSet* mb, int blockno
, struct DoubleARRAY* coords, struct DoubleARRAY* values
, struct IntARRAY* nodeids, struct IntARRAY* globalnodeids
, struct IntARRAY* globalcellids, struct CharARRAY* varnames);
#if USE_PARTICLES
/* virtual void InsertPartData(vtkPolyData* mb_part, int blockno, struct DoubleARRAY* coords,
struct DoubleARRAY* values, struct IntARRAY* nodeids, struct CharARRAY* varnames, struct IntARRAY* components); */
virtual void InsertPartData(vtkMultiBlockDataSet* mb_part, int blockno, struct DoubleARRAY* coords,
struct DoubleARRAY* values, struct IntARRAY* nodeids, struct CharARRAY* varnames, struct IntARRAY* components);
#endif
void DistributeData(vtkMultiBlockDataSet* mb, int blockno);
vtkDataArraySelection* VarDataArraySelection;
vtkDataArraySelection* BCDataArraySelection;
vtkDataArraySelection* VarParticleDataArraySelection;
// The observer to modify this object when the array selections are modified.
vtkCallbackCommand* SelectionObserver;
// Callback registered with the SelectionObserver.
static void SelectionModifiedCallback(vtkObject* caller, unsigned long eid,
void* clientdata, void* calldata);
char* FileName;
int NVisu;
int NCalc;
int UseD3;
int HighOrder;
int UseCurveds;
char* NodeTypeVisu;
int Avg2d;
int DGonly;
char* ParameterFileOverwrite;
char* MeshFileOverwrite;
std::vector<bool> VarNames_selected;
std::vector<bool> BCNames_selected;
std::vector<bool> PartNames_selected;
int NumProcesses;
int ProcessId;
// all loaded filenames, timesteps (multiple for timeseries)
std::vector<std::string> FileNames;
std::vector<double> Timesteps;
int FindClosestTimeStep(double requestedTimeValue);
//void SetNodeTypeVisu(const char* nodetypevisu);
vtkStringArray* GetNodeTypeVisuList();
protected:
visuReader();
~visuReader();
virtual int FillOutputPortInformation(int port, vtkInformation* info);
private:
// MPI
vtkMultiProcessController *Controller;
MPI_Comm mpiComm;
};
#endif //VISUREADER_H
| 7,429 | 35.782178 | 130 |
h
|
flexi-particle
|
flexi-particle-master/src/flexi.h
|
!=================================================================================================================================
! Copyright (c) 2010-2016 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
!===================================================================================================================================
! Here, preprocessor variables for different equation systems and abbreviations for specific expressions are defined
!===================================================================================================================================
! Abbrevations
#ifdef SUN
# define __DATE__ '__TIME__ and __DATE__ not'
# define __TIME__ 'available for SUN COMPILER'
# define IEEE_ISNAN
#elif SX
# define __DATE__ '__TIME__ and __DATE__ not'
# define __TIME__ 'available for SX COMPILER'
#elif PGI
# define NO_ISNAN
#endif
#ifndef __FILENAME__
#define __FILENAME__ __FILE__
#endif
#define __STAMP__ __FILENAME__,__LINE__,__DATE__,__TIME__
#ifdef GNU
# define IEEE_IS_NAN ISNAN
#endif
#define SIZEOF_F(x) (STORAGE_SIZE(x)/8)
#define NO_OP(x) ASSOCIATE( x => x ); END ASSOCIATE
#ifdef GNU
#define CHECKSAFEINT(x,k) IF(x>HUGE(1_ k).OR.x<-HUGE(1_ k)) CALL Abort(__STAMP__,'Integer conversion failed: out of range!')
#define CHECKSAFEREAL(x,k) IF(x>HUGE(1._ k).OR.x<-HUGE(1._ k)) CALL Abort(__STAMP__,'Real conversion failed: out of range!')
#elif CRAY
#define CHECKSAFEINT(x,k)
#define CHECKSAFEREAL(x,k)
#else
#define CHECKSAFEINT(x,k) IF(x>HUGE(1_ ## k).OR.x<-HUGE(1_ ## k)) CALL Abort(__STAMP__,'Integer conversion failed: out of range!')
#define CHECKSAFEREAL(x,k) IF(x>HUGE(1._ ## k).OR.x<-HUGE(1._ ## k)) CALL Abort(__STAMP__,'Real conversion failed: out of range!')
#endif
! Time Step Minimum: dt_Min
#define DT_NVAR 3
#define DT_MIN 1
#define DT_ANALYZE 2
#define DT_END 3
! Test for equality: read description in mathtools.f90 for further infos
#define ALMOSTEQUALABSOLUTE(x,y,tol) (ABS((x)-(y)).LE.(tol))
#define ALMOSTEQUALRELATIVE(x,y,tol) (ABS((x)-(y)).LE.MAX(ABS(x),ABS(y))*(tol))
#define ALMOSTEQUALABSORREL(x,y,tol) (ALMOSTEQUALABSOLUTE(x,y,tol) .OR. ALMOSTEQUALRELATIVE(x,y,tol))
#define ALMOSTEQUALABSANDREL(x,y,tol) (ALMOSTEQUALABSOLUTE(x,y,tol) .AND. ALMOSTEQUALRELATIVE(x,y,tol))
! Define MPI specific write shortcuts
#if USE_MPI
# define SWRITE IF(MPIRoot) WRITE
#if USE_LOADBALANCE
# define LBWRITE IF(MPIRoot.AND..NOT.PerformLoadBalance) WRITE
#else /*USE_LOADBALANCE*/
# define LBWRITE IF(MPIRoot) WRITE
#endif /*USE_LOADBALANCE*/
# define IPWRITE(a,b) WRITE(a,b)myRank,
# define GETTIME(a) a=MPI_WTIME()
#else /*USE_MPI*/
# define SWRITE WRITE
# define LBWRITE WRITE
# define IPWRITE WRITE
# define GETTIME(a) CALL CPU_TIME(a)
#endif /*USE_MPI*/
#define ERRWRITE(a,b) CALL CreateErrFile(); IF(ErrorFiles) WRITE(UNIT_errOut,b)
#define LOGWRITE(a,b) IF(Logging) WRITE(UNIT_logOut,b)
#define SDEALLOCATE(A) IF(ALLOCATED(A)) DEALLOCATE(A)
#define ADEALLOCATE(A) IF(ASSOCIATED(A)) DEALLOCATE(A)
#define PDEALLOCATE(A) IF(PRESENT(A)) THEN; IF(ALLOCATED(A)) DEALLOCATE(A); ENDIF
! Define OpenMP specific shortcuts
#if USE_OPENMP
# define OMP_FLEXITIME() OMP_GET_WTIME()
#else
# define OMP_FLEXITIME() FLEXITIME()
#endif
! Loop variables
#define PP_IJK i,j,k
#define PP_ij i,j
! Predefined "PARAMETER-like" variables
#define XI_MINUS 5
#define XI_PLUS 3
#define ETA_MINUS 2
#define ETA_PLUS 4
#define ZETA_MINUS 1
#define ZETA_PLUS 6
! Entry position in SideToElem
#define S2E_ELEM_ID 1
#define S2E_NB_ELEM_ID 2
#define S2E_LOC_SIDE_ID 3
#define S2E_NB_LOC_SIDE_ID 4
#define S2E_FLIP 5
! Entry position in ElemToSide
#define E2S_SIDE_ID 1
#define E2S_FLIP 2
! Entry position in BC
#define MI_SIDEID 1
#define MI_FLIP 2
! Entry position in BC
#define BC_TYPE 1
#define BC_STATE 2
#define BC_ALPHA 3
! Entry position in BC
#define SEND 1
#define RECV 2
!#define DEBUGMESH
#if FV_ENABLED
#define FV_SIZE 1
#else
#define FV_SIZE 0
#endif
#if !(FV_ENABLED)
#define FV_Elems(x) 0
#define FV_Elems_master(x) 0
#define FV_Elems_slave(x) 0
#define FV_Elems_Sum(x) 0
#endif
! Compute viscous contributions in volume integral
! NOT if FV-Blending or if non-parabolic
#if (FV_ENABLED==2) || !PARABOLIC
#define VOLINT_VISC 0
#else
#define VOLINT_VISC 1
#endif
#define KILL(x) SWRITE(*,*) __FILE__,__LINE__,x; stop
! overintegration
#define CUTOFF 1
#define CUTOFFCONS 2
! PURE debug switch
#if DEBUG
#define PPURE
#else
#define PPURE PURE
#endif
!2d functionality
#if (PP_dim==2)
#define ZDIM(a) 0
#define PP_NZ 0
#define DIMV 1:2
#else
#define ZDIM(a) a
#define PP_NZ PP_N
#define DIMV 1:3
#endif
| 5,628 | 31.165714 | 133 |
h
|
flexi-particle
|
flexi-particle-master/src/equations/linearscalaradvection/eos.h
|
!=================================================================================================================================
! Copyright (c) 2010-2016 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
! Define variables for normal and extended state vector
! Normal U(1:1) with conservative variables
! Extended U(1:2) with conservative and primitive variables
#define CONS 1:PP_nVar /* all cons variables */
#define PRIM 1:PP_nVarPrim /* all prim variables */
#define PP_2Var PP_nVar+PP_nVarPrim
! Lifting
#define PP_nVarLifting 1
#define LIFT_VARS (/1/)
#define PRIM_LIFT (/1/)
| 1,594 | 60.346154 | 130 |
h
|
flexi-particle
|
flexi-particle-master/src/indicator/indicator.h
|
!=================================================================================================================================
! Copyright (c) 2010-2022 Prof. Claus-Dieter Munz
! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods.
! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/
!
! FLEXI 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 3 of the License, or (at your option) any later version.
!
! FLEXI 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 v3.0 for more details.
!
! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>.
!=================================================================================================================================
#define INDTYPE_DG 0
#define INDTYPE_FV 1
#define INDTYPE_PERSSON 2
#define INDTYPE_JAMESON 8
#define INDTYPE_DUCROS 9
#define INDTYPE_DUCROSTIMESJST 10
#define INDTYPE_HALFHALF 3
#define INDTYPE_CHECKERBOARD 33
#define INDTYPE_BOX 66
#define INDTYPE_BLENDING_PERSSON 102
| 1,530 | 60.24 | 130 |
h
|
flexi-particle
|
flexi-particle-master/src/output/read_userblock.c
|
#include <string.h>
#include <stdio.h>
extern char userblock_start;
extern char userblock_end;
extern char userblock_size;
long get_userblock_size_(void)
{
//return (unsigned long)(&userblock_size);
// Fixes mysterious bug occurring on some systems potentially due to the new GCC 7.3
// where userblock_size is wrong though the symbol is correctly defined.
// Since userblock_size = userblock_end - userblock_start , we just compute it on the fly.
return (unsigned long)(&userblock_end-&userblock_start);
}
void insert_userblock(char* filename, char* inifilename)
{
FILE* fp = fopen(filename, "w");
rewind(fp);
fprintf(fp, "{[( START USERBLOCK )]}\n");
// ini file
fprintf(fp, "{[( INIFILE )]}\n");
FILE* fini = fopen(inifilename, "rb");
int c;
do {
c = fgetc (fini);
if (c != EOF) fputc((char)c, fp);
} while (c != EOF);
fclose(fini);
// compressed data ( as tar.xz )
fprintf(fp, "{[( COMPRESSED )]}\n");
fprintf(fp, "userblock.txt\n"); // filename
fprintf(fp, "%ld\n", get_userblock_size_()); // filesize
char* p = &userblock_start;
while ( p != &userblock_end ) fputc(*p++, fp);
fprintf(fp, "\n");
fprintf(fp, "{[( END USERBLOCK )]}\n");
fclose(fp);
}
void copy_userblock(char* outfilename, char* infilename)
{
FILE* fout = fopen(outfilename,"rb+");
FILE* fin = fopen(infilename, "r");
rewind(fout);
int c;
do {
c = fgetc (fin);
if (c != EOF) fputc((char) c, fout);
} while (c != EOF);
fclose(fin);
fclose(fout);
}
| 1,552 | 26.245614 | 93 |
c
|
openssl
|
openssl-master/apps/asn1parse.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/asn1t.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_IN, OPT_OUT, OPT_INDENT, OPT_NOOUT,
OPT_OID, OPT_OFFSET, OPT_LENGTH, OPT_DUMP, OPT_DLIMIT,
OPT_STRPARSE, OPT_GENSTR, OPT_GENCONF, OPT_STRICTPEM,
OPT_ITEM
} OPTION_CHOICE;
const OPTIONS asn1parse_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"oid", OPT_OID, '<', "file of extra oid definitions"},
OPT_SECTION("I/O"),
{"inform", OPT_INFORM, 'A', "input format - one of DER PEM B64"},
{"in", OPT_IN, '<', "input file"},
{"out", OPT_OUT, '>', "output file (output format is always DER)"},
{"noout", OPT_NOOUT, 0, "do not produce any output"},
{"offset", OPT_OFFSET, 'p', "offset into file"},
{"length", OPT_LENGTH, 'p', "length of section in file"},
{"strparse", OPT_STRPARSE, 'p',
"offset; a series of these can be used to 'dig'"},
{"genstr", OPT_GENSTR, 's', "string to generate ASN1 structure from"},
{OPT_MORE_STR, 0, 0, "into multiple ASN1 blob wrappings"},
{"genconf", OPT_GENCONF, 's', "file to generate ASN1 structure from"},
{"strictpem", OPT_STRICTPEM, 0,
"equivalent to '-inform pem' (obsolete)"},
{"item", OPT_ITEM, 's', "item to parse and print"},
{OPT_MORE_STR, 0, 0, "(-inform will be ignored)"},
OPT_SECTION("Formatting"),
{"i", OPT_INDENT, 0, "indents the output"},
{"dump", OPT_DUMP, 0, "unknown data in hex form"},
{"dlimit", OPT_DLIMIT, 'p',
"dump the first arg bytes of unknown data in hex form"},
{NULL}
};
static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf);
int asn1parse_main(int argc, char **argv)
{
ASN1_TYPE *at = NULL;
BIO *in = NULL, *b64 = NULL, *derout = NULL;
BUF_MEM *buf = NULL;
STACK_OF(OPENSSL_STRING) *osk = NULL;
char *genstr = NULL, *genconf = NULL;
char *infile = NULL, *oidfile = NULL, *derfile = NULL;
unsigned char *str = NULL;
char *name = NULL, *header = NULL, *prog;
const unsigned char *ctmpbuf;
int indent = 0, noout = 0, dump = 0, informat = FORMAT_PEM;
int offset = 0, ret = 1, i, j;
long num, tmplen;
unsigned char *tmpbuf;
unsigned int length = 0;
OPTION_CHOICE o;
const ASN1_ITEM *it = NULL;
prog = opt_init(argc, argv, asn1parse_options);
if ((osk = sk_OPENSSL_STRING_new_null()) == NULL) {
BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
goto end;
}
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(asn1parse_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_ASN1, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
derfile = opt_arg();
break;
case OPT_INDENT:
indent = 1;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_OID:
oidfile = opt_arg();
break;
case OPT_OFFSET:
offset = strtol(opt_arg(), NULL, 0);
break;
case OPT_LENGTH:
length = strtol(opt_arg(), NULL, 0);
break;
case OPT_DUMP:
dump = -1;
break;
case OPT_DLIMIT:
dump = strtol(opt_arg(), NULL, 0);
break;
case OPT_STRPARSE:
sk_OPENSSL_STRING_push(osk, opt_arg());
break;
case OPT_GENSTR:
genstr = opt_arg();
break;
case OPT_GENCONF:
genconf = opt_arg();
break;
case OPT_STRICTPEM:
/* accepted for backward compatibility */
informat = FORMAT_PEM;
break;
case OPT_ITEM:
it = ASN1_ITEM_lookup(opt_arg());
if (it == NULL) {
size_t tmp;
BIO_printf(bio_err, "Unknown item name %s\n", opt_arg());
BIO_puts(bio_err, "Supported types:\n");
for (tmp = 0;; tmp++) {
it = ASN1_ITEM_get(tmp);
if (it == NULL)
break;
BIO_printf(bio_err, " %s\n", it->sname);
}
goto end;
}
break;
}
}
/* No extra args. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (oidfile != NULL) {
in = bio_open_default(oidfile, 'r', FORMAT_TEXT);
if (in == NULL)
goto end;
OBJ_create_objects(in);
BIO_free(in);
}
if ((in = bio_open_default(infile, 'r', informat)) == NULL)
goto end;
if (derfile && (derout = bio_open_default(derfile, 'w', FORMAT_ASN1)) == NULL)
goto end;
if ((buf = BUF_MEM_new()) == NULL)
goto end;
if (informat == FORMAT_PEM) {
if (PEM_read_bio(in, &name, &header, &str, &num) != 1) {
BIO_printf(bio_err, "Error reading PEM file\n");
ERR_print_errors(bio_err);
goto end;
}
buf->data = (char *)str;
buf->length = buf->max = num;
} else {
if (!BUF_MEM_grow(buf, BUFSIZ * 8))
goto end; /* Pre-allocate :-) */
if (genstr || genconf) {
num = do_generate(genstr, genconf, buf);
if (num < 0) {
ERR_print_errors(bio_err);
goto end;
}
} else {
if (informat == FORMAT_BASE64) {
BIO *tmp;
if ((b64 = BIO_new(BIO_f_base64())) == NULL)
goto end;
BIO_push(b64, in);
tmp = in;
in = b64;
b64 = tmp;
}
num = 0;
for (;;) {
if (!BUF_MEM_grow(buf, num + BUFSIZ))
goto end;
i = BIO_read(in, &(buf->data[num]), BUFSIZ);
if (i <= 0)
break;
num += i;
}
}
str = (unsigned char *)buf->data;
}
/* If any structs to parse go through in sequence */
if (sk_OPENSSL_STRING_num(osk)) {
tmpbuf = str;
tmplen = num;
for (i = 0; i < sk_OPENSSL_STRING_num(osk); i++) {
ASN1_TYPE *atmp;
int typ;
j = strtol(sk_OPENSSL_STRING_value(osk, i), NULL, 0);
if (j <= 0 || j >= tmplen) {
BIO_printf(bio_err, "'%s' is out of range\n",
sk_OPENSSL_STRING_value(osk, i));
continue;
}
tmpbuf += j;
tmplen -= j;
atmp = at;
ctmpbuf = tmpbuf;
at = d2i_ASN1_TYPE(NULL, &ctmpbuf, tmplen);
ASN1_TYPE_free(atmp);
if (!at) {
BIO_printf(bio_err, "Error parsing structure\n");
ERR_print_errors(bio_err);
goto end;
}
typ = ASN1_TYPE_get(at);
if ((typ == V_ASN1_OBJECT)
|| (typ == V_ASN1_BOOLEAN)
|| (typ == V_ASN1_NULL)) {
BIO_printf(bio_err, "Can't parse %s type\n", ASN1_tag2str(typ));
ERR_print_errors(bio_err);
goto end;
}
/* hmm... this is a little evil but it works */
tmpbuf = at->value.asn1_string->data;
tmplen = at->value.asn1_string->length;
}
str = tmpbuf;
num = tmplen;
}
if (offset < 0 || offset >= num) {
BIO_printf(bio_err, "Error: offset out of range\n");
goto end;
}
num -= offset;
if (length == 0 || length > (unsigned int)num)
length = (unsigned int)num;
if (derout != NULL) {
if (BIO_write(derout, str + offset, length) != (int)length) {
BIO_printf(bio_err, "Error writing output\n");
ERR_print_errors(bio_err);
goto end;
}
}
if (!noout) {
const unsigned char *p = str + offset;
if (it != NULL) {
ASN1_VALUE *value = ASN1_item_d2i(NULL, &p, length, it);
if (value == NULL) {
BIO_printf(bio_err, "Error parsing item %s\n", it->sname);
ERR_print_errors(bio_err);
goto end;
}
ASN1_item_print(bio_out, value, 0, it, NULL);
ASN1_item_free(value, it);
} else {
if (!ASN1_parse_dump(bio_out, p, length, indent, dump)) {
ERR_print_errors(bio_err);
goto end;
}
}
}
ret = 0;
end:
BIO_free(derout);
BIO_free(in);
BIO_free(b64);
if (ret != 0)
ERR_print_errors(bio_err);
BUF_MEM_free(buf);
OPENSSL_free(name);
OPENSSL_free(header);
ASN1_TYPE_free(at);
sk_OPENSSL_STRING_free(osk);
return ret;
}
static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf)
{
CONF *cnf = NULL;
int len;
unsigned char *p;
ASN1_TYPE *atyp = NULL;
if (genconf != NULL) {
if ((cnf = app_load_config(genconf)) == NULL)
goto err;
if (genstr == NULL)
genstr = NCONF_get_string(cnf, "default", "asn1");
if (genstr == NULL) {
BIO_printf(bio_err, "Can't find 'asn1' in '%s'\n", genconf);
goto err;
}
}
atyp = ASN1_generate_nconf(genstr, cnf);
NCONF_free(cnf);
cnf = NULL;
if (atyp == NULL)
return -1;
len = i2d_ASN1_TYPE(atyp, NULL);
if (len <= 0)
goto err;
if (!BUF_MEM_grow(buf, len))
goto err;
p = (unsigned char *)buf->data;
i2d_ASN1_TYPE(atyp, &p);
ASN1_TYPE_free(atyp);
return len;
err:
NCONF_free(cnf);
ASN1_TYPE_free(atyp);
return -1;
}
| 10,652 | 28.428177 | 82 |
c
|
openssl
|
openssl-master/apps/ciphers.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/err.h>
#include <openssl/ssl.h>
#include "s_apps.h"
typedef enum OPTION_choice {
OPT_COMMON,
OPT_STDNAME,
OPT_CONVERT,
OPT_SSL3,
OPT_TLS1,
OPT_TLS1_1,
OPT_TLS1_2,
OPT_TLS1_3,
OPT_PSK,
OPT_SRP,
OPT_CIPHERSUITES,
OPT_V, OPT_UPPER_V, OPT_S, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS ciphers_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [cipher]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("Output"),
{"v", OPT_V, '-', "Verbose listing of the SSL/TLS ciphers"},
{"V", OPT_UPPER_V, '-', "Even more verbose"},
{"stdname", OPT_STDNAME, '-', "Show standard cipher names"},
{"convert", OPT_CONVERT, 's', "Convert standard name into OpenSSL name"},
OPT_SECTION("Cipher specification"),
{"s", OPT_S, '-', "Only supported ciphers"},
#ifndef OPENSSL_NO_SSL3
{"ssl3", OPT_SSL3, '-', "Ciphers compatible with SSL3"},
#endif
#ifndef OPENSSL_NO_TLS1
{"tls1", OPT_TLS1, '-', "Ciphers compatible with TLS1"},
#endif
#ifndef OPENSSL_NO_TLS1_1
{"tls1_1", OPT_TLS1_1, '-', "Ciphers compatible with TLS1.1"},
#endif
#ifndef OPENSSL_NO_TLS1_2
{"tls1_2", OPT_TLS1_2, '-', "Ciphers compatible with TLS1.2"},
#endif
#ifndef OPENSSL_NO_TLS1_3
{"tls1_3", OPT_TLS1_3, '-', "Ciphers compatible with TLS1.3"},
#endif
#ifndef OPENSSL_NO_PSK
{"psk", OPT_PSK, '-', "Include ciphersuites requiring PSK"},
#endif
#ifndef OPENSSL_NO_SRP
{"srp", OPT_SRP, '-', "(deprecated) Include ciphersuites requiring SRP"},
#endif
{"ciphersuites", OPT_CIPHERSUITES, 's',
"Configure the TLSv1.3 ciphersuites to use"},
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"cipher", 0, 0, "Cipher string to decode (optional)"},
{NULL}
};
#ifndef OPENSSL_NO_PSK
static unsigned int dummy_psk(SSL *ssl, const char *hint, char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len)
{
return 0;
}
#endif
int ciphers_main(int argc, char **argv)
{
SSL_CTX *ctx = NULL;
SSL *ssl = NULL;
STACK_OF(SSL_CIPHER) *sk = NULL;
const SSL_METHOD *meth = TLS_server_method();
int ret = 1, i, verbose = 0, Verbose = 0, use_supported = 0;
int stdname = 0;
#ifndef OPENSSL_NO_PSK
int psk = 0;
#endif
#ifndef OPENSSL_NO_SRP
int srp = 0;
#endif
const char *p;
char *ciphers = NULL, *prog, *convert = NULL, *ciphersuites = NULL;
char buf[512];
OPTION_CHOICE o;
int min_version = 0, max_version = 0;
prog = opt_init(argc, argv, ciphers_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(ciphers_options);
ret = 0;
goto end;
case OPT_V:
verbose = 1;
break;
case OPT_UPPER_V:
verbose = Verbose = 1;
break;
case OPT_S:
use_supported = 1;
break;
case OPT_STDNAME:
stdname = verbose = 1;
break;
case OPT_CONVERT:
convert = opt_arg();
break;
case OPT_SSL3:
min_version = SSL3_VERSION;
max_version = SSL3_VERSION;
break;
case OPT_TLS1:
min_version = TLS1_VERSION;
max_version = TLS1_VERSION;
break;
case OPT_TLS1_1:
min_version = TLS1_1_VERSION;
max_version = TLS1_1_VERSION;
break;
case OPT_TLS1_2:
min_version = TLS1_2_VERSION;
max_version = TLS1_2_VERSION;
break;
case OPT_TLS1_3:
min_version = TLS1_3_VERSION;
max_version = TLS1_3_VERSION;
break;
case OPT_PSK:
#ifndef OPENSSL_NO_PSK
psk = 1;
#endif
break;
case OPT_SRP:
#ifndef OPENSSL_NO_SRP
srp = 1;
#endif
break;
case OPT_CIPHERSUITES:
ciphersuites = opt_arg();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Optional arg is cipher name. */
argv = opt_rest();
if (opt_num_rest() == 1)
ciphers = argv[0];
else if (!opt_check_rest_arg(NULL))
goto opthelp;
if (convert != NULL) {
BIO_printf(bio_out, "OpenSSL cipher name: %s\n",
OPENSSL_cipher_name(convert));
ret = 0;
goto end;
}
ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
if (ctx == NULL)
goto err;
if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
goto err;
if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
goto err;
#ifndef OPENSSL_NO_PSK
if (psk)
SSL_CTX_set_psk_client_callback(ctx, dummy_psk);
#endif
#ifndef OPENSSL_NO_SRP
if (srp)
set_up_dummy_srp(ctx);
#endif
if (ciphersuites != NULL && !SSL_CTX_set_ciphersuites(ctx, ciphersuites)) {
BIO_printf(bio_err, "Error setting TLSv1.3 ciphersuites\n");
goto err;
}
if (ciphers != NULL) {
if (!SSL_CTX_set_cipher_list(ctx, ciphers)) {
BIO_printf(bio_err, "Error in cipher list\n");
goto err;
}
}
ssl = SSL_new(ctx);
if (ssl == NULL)
goto err;
if (use_supported)
sk = SSL_get1_supported_ciphers(ssl);
else
sk = SSL_get_ciphers(ssl);
if (!verbose) {
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, i);
if (!ossl_assert(c != NULL))
continue;
p = SSL_CIPHER_get_name(c);
if (p == NULL)
break;
if (i != 0)
BIO_printf(bio_out, ":");
BIO_printf(bio_out, "%s", p);
}
BIO_printf(bio_out, "\n");
} else {
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
const SSL_CIPHER *c;
c = sk_SSL_CIPHER_value(sk, i);
if (!ossl_assert(c != NULL))
continue;
if (Verbose) {
unsigned long id = SSL_CIPHER_get_id(c);
int id0 = (int)(id >> 24);
int id1 = (int)((id >> 16) & 0xffL);
int id2 = (int)((id >> 8) & 0xffL);
int id3 = (int)(id & 0xffL);
if ((id & 0xff000000L) == 0x03000000L)
BIO_printf(bio_out, " 0x%02X,0x%02X - ", id2, id3); /* SSL3
* cipher */
else
BIO_printf(bio_out, "0x%02X,0x%02X,0x%02X,0x%02X - ", id0, id1, id2, id3); /* whatever */
}
if (stdname) {
const char *nm = SSL_CIPHER_standard_name(c);
if (nm == NULL)
nm = "UNKNOWN";
BIO_printf(bio_out, "%-45s - ", nm);
}
BIO_puts(bio_out, SSL_CIPHER_description(c, buf, sizeof(buf)));
}
}
ret = 0;
goto end;
err:
ERR_print_errors(bio_err);
end:
if (use_supported)
sk_SSL_CIPHER_free(sk);
SSL_CTX_free(ctx);
SSL_free(ssl);
return ret;
}
| 7,967 | 26.957895 | 109 |
c
|
openssl
|
openssl-master/apps/crl.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_IN, OPT_OUTFORM, OPT_OUT, OPT_KEYFORM, OPT_KEY,
OPT_ISSUER, OPT_LASTUPDATE, OPT_NEXTUPDATE, OPT_FINGERPRINT,
OPT_CRLNUMBER, OPT_BADSIG, OPT_GENDELTA, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE,
OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_VERIFY, OPT_DATEOPT, OPT_TEXT, OPT_HASH,
OPT_HASH_OLD, OPT_NOOUT, OPT_NAMEOPT, OPT_MD, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS crl_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"verify", OPT_VERIFY, '-', "Verify CRL signature"},
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file - default stdin"},
{"inform", OPT_INFORM, 'F', "CRL input format (DER or PEM); has no effect"},
{"key", OPT_KEY, '<', "CRL signing Private key to use"},
{"keyform", OPT_KEYFORM, 'F', "Private key file format (DER/PEM/P12); has no effect"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "output file - default stdout"},
{"outform", OPT_OUTFORM, 'F', "Output format - default PEM"},
{"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."},
{"text", OPT_TEXT, '-', "Print out a text format version"},
{"hash", OPT_HASH, '-', "Print hash value"},
#ifndef OPENSSL_NO_MD5
{"hash_old", OPT_HASH_OLD, '-', "Print old-style (MD5) hash value"},
#endif
{"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
{"", OPT_MD, '-', "Any supported digest"},
OPT_SECTION("CRL"),
{"issuer", OPT_ISSUER, '-', "Print issuer DN"},
{"lastupdate", OPT_LASTUPDATE, '-', "Set lastUpdate field"},
{"nextupdate", OPT_NEXTUPDATE, '-', "Set nextUpdate field"},
{"noout", OPT_NOOUT, '-', "No CRL output"},
{"fingerprint", OPT_FINGERPRINT, '-', "Print the crl fingerprint"},
{"crlnumber", OPT_CRLNUMBER, '-', "Print CRL number"},
{"badsig", OPT_BADSIG, '-', "Corrupt last byte of loaded CRL signature (for test)" },
{"gendelta", OPT_GENDELTA, '<', "Other CRL to compare/diff to the Input one"},
OPT_SECTION("Certificate"),
{"CApath", OPT_CAPATH, '/', "Verify CRL using certificates in dir"},
{"CAfile", OPT_CAFILE, '<', "Verify CRL using certificates in file name"},
{"CAstore", OPT_CASTORE, ':', "Verify CRL using certificates in store URI"},
{"no-CAfile", OPT_NOCAFILE, '-',
"Do not load the default certificates file"},
{"no-CApath", OPT_NOCAPATH, '-',
"Do not load certificates from the default certificates directory"},
{"no-CAstore", OPT_NOCASTORE, '-',
"Do not load certificates from the default certificates store"},
OPT_PROV_OPTIONS,
{NULL}
};
int crl_main(int argc, char **argv)
{
X509_CRL *x = NULL;
BIO *out = NULL;
X509_STORE *store = NULL;
X509_STORE_CTX *ctx = NULL;
X509_LOOKUP *lookup = NULL;
X509_OBJECT *xobj = NULL;
EVP_PKEY *pkey;
EVP_MD *digest = (EVP_MD *)EVP_sha1();
char *infile = NULL, *outfile = NULL, *crldiff = NULL, *keyfile = NULL;
char *digestname = NULL;
const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog;
OPTION_CHOICE o;
int hash = 0, issuer = 0, lastupdate = 0, nextupdate = 0, noout = 0;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyformat = FORMAT_UNDEF;
int ret = 1, num = 0, badsig = 0, fingerprint = 0, crlnumber = 0;
int text = 0, do_ver = 0, noCAfile = 0, noCApath = 0, noCAstore = 0;
unsigned long dateopt = ASN1_DTFLGS_RFC822;
int i;
#ifndef OPENSSL_NO_MD5
int hash_old = 0;
#endif
opt_set_unknown_name("digest");
prog = opt_init(argc, argv, crl_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(crl_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
goto opthelp;
break;
case OPT_KEY:
keyfile = opt_arg();
break;
case OPT_GENDELTA:
crldiff = opt_arg();
break;
case OPT_CAPATH:
CApath = opt_arg();
do_ver = 1;
break;
case OPT_CAFILE:
CAfile = opt_arg();
do_ver = 1;
break;
case OPT_CASTORE:
CAstore = opt_arg();
do_ver = 1;
break;
case OPT_NOCAPATH:
noCApath = 1;
break;
case OPT_NOCAFILE:
noCAfile = 1;
break;
case OPT_NOCASTORE:
noCAstore = 1;
break;
case OPT_HASH_OLD:
#ifndef OPENSSL_NO_MD5
hash_old = ++num;
#endif
break;
case OPT_VERIFY:
do_ver = 1;
break;
case OPT_DATEOPT:
if (!set_dateopt(&dateopt, opt_arg()))
goto opthelp;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_HASH:
hash = ++num;
break;
case OPT_ISSUER:
issuer = ++num;
break;
case OPT_LASTUPDATE:
lastupdate = ++num;
break;
case OPT_NEXTUPDATE:
nextupdate = ++num;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_FINGERPRINT:
fingerprint = ++num;
break;
case OPT_CRLNUMBER:
crlnumber = ++num;
break;
case OPT_BADSIG:
badsig = 1;
break;
case OPT_NAMEOPT:
if (!set_nameopt(opt_arg()))
goto opthelp;
break;
case OPT_MD:
digestname = opt_unknown();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No remaining args. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!opt_md(digestname, &digest))
goto opthelp;
x = load_crl(infile, informat, 1, "CRL");
if (x == NULL)
goto end;
if (do_ver) {
if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore)) == NULL)
goto end;
lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
if (lookup == NULL)
goto end;
ctx = X509_STORE_CTX_new();
if (ctx == NULL || !X509_STORE_CTX_init(ctx, store, NULL, NULL)) {
BIO_printf(bio_err, "Error initialising X509 store\n");
goto end;
}
xobj = X509_STORE_CTX_get_obj_by_subject(ctx, X509_LU_X509,
X509_CRL_get_issuer(x));
if (xobj == NULL) {
BIO_printf(bio_err, "Error getting CRL issuer certificate\n");
goto end;
}
pkey = X509_get_pubkey(X509_OBJECT_get0_X509(xobj));
X509_OBJECT_free(xobj);
if (pkey == NULL) {
BIO_printf(bio_err, "Error getting CRL issuer public key\n");
goto end;
}
i = X509_CRL_verify(x, pkey);
EVP_PKEY_free(pkey);
if (i < 0)
goto end;
if (i == 0)
BIO_printf(bio_err, "verify failure\n");
else
BIO_printf(bio_err, "verify OK\n");
}
if (crldiff != NULL) {
X509_CRL *newcrl, *delta;
if (!keyfile) {
BIO_puts(bio_err, "Missing CRL signing key\n");
goto end;
}
newcrl = load_crl(crldiff, informat, 0, "other CRL");
if (!newcrl)
goto end;
pkey = load_key(keyfile, keyformat, 0, NULL, NULL, "CRL signing key");
if (pkey == NULL) {
X509_CRL_free(newcrl);
goto end;
}
delta = X509_CRL_diff(x, newcrl, pkey, digest, 0);
X509_CRL_free(newcrl);
EVP_PKEY_free(pkey);
if (delta) {
X509_CRL_free(x);
x = delta;
} else {
BIO_puts(bio_err, "Error creating delta CRL\n");
goto end;
}
}
if (badsig) {
const ASN1_BIT_STRING *sig;
X509_CRL_get0_signature(x, &sig, NULL);
corrupt_signature(sig);
}
if (num) {
for (i = 1; i <= num; i++) {
if (issuer == i) {
print_name(bio_out, "issuer=", X509_CRL_get_issuer(x));
}
if (crlnumber == i) {
ASN1_INTEGER *crlnum;
crlnum = X509_CRL_get_ext_d2i(x, NID_crl_number, NULL, NULL);
BIO_printf(bio_out, "crlNumber=");
if (crlnum) {
BIO_puts(bio_out, "0x");
i2a_ASN1_INTEGER(bio_out, crlnum);
ASN1_INTEGER_free(crlnum);
} else {
BIO_puts(bio_out, "<NONE>");
}
BIO_printf(bio_out, "\n");
}
if (hash == i) {
int ok;
unsigned long hash_value =
X509_NAME_hash_ex(X509_CRL_get_issuer(x), app_get0_libctx(),
app_get0_propq(), &ok);
if (num > 1)
BIO_printf(bio_out, "issuer name hash=");
if (ok) {
BIO_printf(bio_out, "%08lx\n", hash_value);
} else {
BIO_puts(bio_out, "<ERROR>");
goto end;
}
}
#ifndef OPENSSL_NO_MD5
if (hash_old == i) {
if (num > 1)
BIO_printf(bio_out, "issuer name old hash=");
BIO_printf(bio_out, "%08lx\n",
X509_NAME_hash_old(X509_CRL_get_issuer(x)));
}
#endif
if (lastupdate == i) {
BIO_printf(bio_out, "lastUpdate=");
ASN1_TIME_print_ex(bio_out, X509_CRL_get0_lastUpdate(x), dateopt);
BIO_printf(bio_out, "\n");
}
if (nextupdate == i) {
BIO_printf(bio_out, "nextUpdate=");
if (X509_CRL_get0_nextUpdate(x))
ASN1_TIME_print_ex(bio_out, X509_CRL_get0_nextUpdate(x), dateopt);
else
BIO_printf(bio_out, "NONE");
BIO_printf(bio_out, "\n");
}
if (fingerprint == i) {
int j;
unsigned int n;
unsigned char md[EVP_MAX_MD_SIZE];
if (!X509_CRL_digest(x, digest, md, &n)) {
BIO_printf(bio_err, "out of memory\n");
goto end;
}
BIO_printf(bio_out, "%s Fingerprint=",
EVP_MD_get0_name(digest));
for (j = 0; j < (int)n; j++) {
BIO_printf(bio_out, "%02X%c", md[j], (j + 1 == (int)n)
? '\n' : ':');
}
}
}
}
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
if (text)
X509_CRL_print_ex(out, x, get_nameopt());
if (noout) {
ret = 0;
goto end;
}
if (outformat == FORMAT_ASN1)
i = (int)i2d_X509_CRL_bio(out, x);
else
i = PEM_write_bio_X509_CRL(out, x);
if (!i) {
BIO_printf(bio_err, "unable to write CRL\n");
goto end;
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
BIO_free_all(out);
EVP_MD_free(digest);
X509_CRL_free(x);
X509_STORE_CTX_free(ctx);
X509_STORE_free(store);
return ret;
}
| 12,875 | 31.597468 | 112 |
c
|
openssl
|
openssl-master/apps/crl2pkcs7.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include "apps.h"
#include "progs.h"
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pkcs7.h>
#include <openssl/pem.h>
#include <openssl/objects.h>
static int add_certs_from_file(STACK_OF(X509) *stack, char *certfile);
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_NOCRL, OPT_CERTFILE,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS crl2pkcs7_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
{"nocrl", OPT_NOCRL, '-', "No crl to load, just certs from '-certfile'"},
{"certfile", OPT_CERTFILE, '<',
"File of chain of certs to a trusted CA; can be repeated"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
OPT_PROV_OPTIONS,
{NULL}
};
int crl2pkcs7_main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL;
PKCS7 *p7 = NULL;
PKCS7_SIGNED *p7s = NULL;
STACK_OF(OPENSSL_STRING) *certflst = NULL;
STACK_OF(X509) *cert_stack = NULL;
STACK_OF(X509_CRL) *crl_stack = NULL;
X509_CRL *crl = NULL;
char *infile = NULL, *outfile = NULL, *prog, *certfile;
int i = 0, informat = FORMAT_PEM, outformat = FORMAT_PEM, ret = 1, nocrl =
0;
OPTION_CHOICE o;
prog = opt_init(argc, argv, crl2pkcs7_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(crl2pkcs7_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_NOCRL:
nocrl = 1;
break;
case OPT_CERTFILE:
if ((certflst == NULL)
&& (certflst = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
if (!sk_OPENSSL_STRING_push(certflst, opt_arg()))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No remaining args. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!nocrl) {
in = bio_open_default(infile, 'r', informat);
if (in == NULL)
goto end;
if (informat == FORMAT_ASN1)
crl = d2i_X509_CRL_bio(in, NULL);
else if (informat == FORMAT_PEM)
crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
if (crl == NULL) {
BIO_printf(bio_err, "unable to load CRL\n");
ERR_print_errors(bio_err);
goto end;
}
}
if ((p7 = PKCS7_new()) == NULL)
goto end;
if ((p7s = PKCS7_SIGNED_new()) == NULL)
goto end;
p7->type = OBJ_nid2obj(NID_pkcs7_signed);
p7->d.sign = p7s;
p7s->contents->type = OBJ_nid2obj(NID_pkcs7_data);
if (!ASN1_INTEGER_set(p7s->version, 1))
goto end;
if (crl != NULL) {
if ((crl_stack = sk_X509_CRL_new_null()) == NULL)
goto end;
p7s->crl = crl_stack;
sk_X509_CRL_push(crl_stack, crl);
crl = NULL; /* now part of p7 for OPENSSL_freeing */
}
if (certflst != NULL) {
if ((cert_stack = sk_X509_new_null()) == NULL)
goto end;
p7s->cert = cert_stack;
for (i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) {
certfile = sk_OPENSSL_STRING_value(certflst, i);
if (add_certs_from_file(cert_stack, certfile) < 0) {
BIO_printf(bio_err, "error loading certificates\n");
ERR_print_errors(bio_err);
goto end;
}
}
}
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
if (outformat == FORMAT_ASN1)
i = i2d_PKCS7_bio(out, p7);
else if (outformat == FORMAT_PEM)
i = PEM_write_bio_PKCS7(out, p7);
if (!i) {
BIO_printf(bio_err, "unable to write pkcs7 object\n");
ERR_print_errors(bio_err);
goto end;
}
ret = 0;
end:
sk_OPENSSL_STRING_free(certflst);
BIO_free(in);
BIO_free_all(out);
PKCS7_free(p7);
X509_CRL_free(crl);
return ret;
}
/*-
*----------------------------------------------------------------------
* int add_certs_from_file
*
* Read a list of certificates to be checked from a file.
*
* Results:
* number of certs added if successful, -1 if not.
*----------------------------------------------------------------------
*/
static int add_certs_from_file(STACK_OF(X509) *stack, char *certfile)
{
BIO *in = NULL;
int count = 0;
int ret = -1;
STACK_OF(X509_INFO) *sk = NULL;
X509_INFO *xi;
in = BIO_new_file(certfile, "r");
if (in == NULL) {
BIO_printf(bio_err, "error opening the file, %s\n", certfile);
goto end;
}
/* This loads from a file, a stack of x509/crl/pkey sets */
sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
if (sk == NULL) {
BIO_printf(bio_err, "error reading the file, %s\n", certfile);
goto end;
}
/* scan over it and pull out the CRL's */
while (sk_X509_INFO_num(sk)) {
xi = sk_X509_INFO_shift(sk);
if (xi->x509 != NULL) {
sk_X509_push(stack, xi->x509);
xi->x509 = NULL;
count++;
}
X509_INFO_free(xi);
}
ret = count;
end:
/* never need to OPENSSL_free x */
BIO_free(in);
sk_X509_INFO_free(sk);
return ret;
}
| 6,587 | 27.274678 | 78 |
c
|
openssl
|
openssl-master/apps/dhparam.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/dsa.h>
#include <openssl/dh.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/core_names.h>
#include <openssl/core_dispatch.h>
#include <openssl/param_build.h>
#include <openssl/encoder.h>
#include <openssl/decoder.h>
#define DEFBITS 2048
static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh);
static int verbose = 1;
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT,
OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT,
OPT_DSAPARAM, OPT_2, OPT_3, OPT_5, OPT_VERBOSE, OPT_QUIET,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS dhparam_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"check", OPT_CHECK, '-', "Check the DH parameters"},
#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_DEPRECATED_3_0)
{"dsaparam", OPT_DSAPARAM, '-',
"Read or generate DSA parameters, convert to DH"},
#endif
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"inform", OPT_INFORM, 'F', "Input format, DER or PEM"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'F', "Output format, DER or PEM"},
{"text", OPT_TEXT, '-', "Print a text form of the DH parameters"},
{"noout", OPT_NOOUT, '-', "Don't output any DH parameters"},
{"2", OPT_2, '-', "Generate parameters using 2 as the generator value"},
{"3", OPT_3, '-', "Generate parameters using 3 as the generator value"},
{"5", OPT_5, '-', "Generate parameters using 5 as the generator value"},
{"verbose", OPT_VERBOSE, '-', "Verbose output"},
{"quiet", OPT_QUIET, '-', "Terse output"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"numbits", 0, 0, "Number of bits if generating parameters (optional)"},
{NULL}
};
int dhparam_main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL;
EVP_PKEY *pkey = NULL, *tmppkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
char *infile = NULL, *outfile = NULL, *prog;
ENGINE *e = NULL;
int dsaparam = 0;
int text = 0, ret = 1, num = 0, g = 0;
int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
OPTION_CHOICE o;
prog = opt_init(argc, argv, dhparam_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(dhparam_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_CHECK:
check = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_DSAPARAM:
dsaparam = 1;
break;
case OPT_2:
g = 2;
break;
case OPT_3:
g = 3;
break;
case OPT_5:
g = 5;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_QUIET:
verbose = 0;
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* One optional argument, bitsize to generate. */
argc = opt_num_rest();
argv = opt_rest();
if (argc == 1) {
if (!opt_int(argv[0], &num) || num <= 0)
goto opthelp;
} else if (!opt_check_rest_arg(NULL)) {
goto opthelp;
}
if (!app_RAND_load())
goto end;
if (g && !num)
num = DEFBITS;
if (dsaparam && g) {
BIO_printf(bio_err,
"Error, generator may not be chosen for DSA parameters\n");
goto end;
}
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
/* DH parameters */
if (num && !g)
g = 2;
if (num) {
const char *alg = dsaparam ? "DSA" : "DH";
if (infile != NULL) {
BIO_printf(bio_err, "Warning, input file %s ignored\n", infile);
}
ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), alg, app_get0_propq());
if (ctx == NULL) {
BIO_printf(bio_err,
"Error, %s param generation context allocation failed\n",
alg);
goto end;
}
EVP_PKEY_CTX_set_app_data(ctx, bio_err);
if (verbose) {
EVP_PKEY_CTX_set_cb(ctx, progress_cb);
BIO_printf(bio_err,
"Generating %s parameters, %d bit long %sprime\n",
alg, num, dsaparam ? "" : "safe ");
}
if (EVP_PKEY_paramgen_init(ctx) <= 0) {
BIO_printf(bio_err,
"Error, unable to initialise %s parameters\n",
alg);
goto end;
}
if (dsaparam) {
if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num) <= 0) {
BIO_printf(bio_err, "Error, unable to set DSA prime length\n");
goto end;
}
} else {
if (EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, num) <= 0) {
BIO_printf(bio_err, "Error, unable to set DH prime length\n");
goto end;
}
if (EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, g) <= 0) {
BIO_printf(bio_err, "Error, unable to set generator\n");
goto end;
}
}
tmppkey = app_paramgen(ctx, alg);
EVP_PKEY_CTX_free(ctx);
ctx = NULL;
if (dsaparam) {
pkey = dsa_to_dh(tmppkey);
if (pkey == NULL)
goto end;
EVP_PKEY_free(tmppkey);
} else {
pkey = tmppkey;
}
tmppkey = NULL;
} else {
OSSL_DECODER_CTX *decoderctx = NULL;
const char *keytype = "DH";
int done;
in = bio_open_default(infile, 'r', informat);
if (in == NULL)
goto end;
do {
/*
* We assume we're done unless we explicitly want to retry and set
* this to 0 below.
*/
done = 1;
/*
* We set NULL for the keytype to allow any key type. We don't know
* if we're going to get DH or DHX (or DSA in the event of dsaparam).
* We check that we got one of those key types afterwards.
*/
decoderctx
= OSSL_DECODER_CTX_new_for_pkey(&tmppkey,
(informat == FORMAT_ASN1)
? "DER" : "PEM",
NULL,
(informat == FORMAT_ASN1)
? keytype : NULL,
OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
NULL, NULL);
if (decoderctx != NULL
&& !OSSL_DECODER_from_bio(decoderctx, in)
&& informat == FORMAT_ASN1
&& strcmp(keytype, "DH") == 0) {
/*
* When reading DER we explicitly state the expected keytype
* because, unlike PEM, there is no header to declare what
* the contents of the DER file are. The decoders just try
* and guess. Unfortunately with DHX key types they may guess
* wrong and think we have a DSA keytype. Therefore, we try
* both DH and DHX sequentially.
*/
keytype = "DHX";
/*
* BIO_reset() returns 0 for success for file BIOs only!!!
* This won't work for stdin (and never has done)
*/
if (BIO_reset(in) == 0)
done = 0;
}
OSSL_DECODER_CTX_free(decoderctx);
} while (!done);
if (tmppkey == NULL) {
BIO_printf(bio_err, "Error, unable to load parameters\n");
goto end;
}
if (dsaparam) {
if (!EVP_PKEY_is_a(tmppkey, "DSA")) {
BIO_printf(bio_err, "Error, unable to load DSA parameters\n");
goto end;
}
pkey = dsa_to_dh(tmppkey);
if (pkey == NULL)
goto end;
} else {
if (!EVP_PKEY_is_a(tmppkey, "DH")
&& !EVP_PKEY_is_a(tmppkey, "DHX")) {
BIO_printf(bio_err, "Error, unable to load DH parameters\n");
goto end;
}
pkey = tmppkey;
tmppkey = NULL;
}
}
if (text)
EVP_PKEY_print_params(out, pkey, 4, NULL);
if (check) {
ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq());
if (ctx == NULL) {
BIO_printf(bio_err, "Error, failed to check DH parameters\n");
goto end;
}
if (EVP_PKEY_param_check(ctx) <= 0) {
BIO_printf(bio_err, "Error, invalid parameters generated\n");
goto end;
}
BIO_printf(bio_err, "DH parameters appear to be ok.\n");
}
if (!noout) {
OSSL_ENCODER_CTX *ectx =
OSSL_ENCODER_CTX_new_for_pkey(pkey,
OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
outformat == FORMAT_ASN1
? "DER" : "PEM",
NULL, NULL);
if (ectx == NULL || !OSSL_ENCODER_to_bio(ectx, out)) {
OSSL_ENCODER_CTX_free(ectx);
BIO_printf(bio_err, "Error, unable to write DH parameters\n");
goto end;
}
OSSL_ENCODER_CTX_free(ectx);
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
BIO_free(in);
BIO_free_all(out);
EVP_PKEY_free(pkey);
EVP_PKEY_free(tmppkey);
EVP_PKEY_CTX_free(ctx);
release_engine(e);
return ret;
}
/*
* Historically we had the low-level call DSA_dup_DH() to do this.
* That is now deprecated with no replacement. Since we still need to do this
* for backwards compatibility reasons, we do it "manually".
*/
static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh)
{
OSSL_PARAM_BLD *tmpl = NULL;
OSSL_PARAM *params = NULL;
BIGNUM *bn_p = NULL, *bn_q = NULL, *bn_g = NULL;
EVP_PKEY_CTX *ctx = NULL;
EVP_PKEY *pkey = NULL;
if (!EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_P, &bn_p)
|| !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_Q, &bn_q)
|| !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_G, &bn_g)) {
BIO_printf(bio_err, "Error, failed to set DH parameters\n");
goto err;
}
if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P,
bn_p)
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q,
bn_q)
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G,
bn_g)
|| (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
BIO_printf(bio_err, "Error, failed to set DH parameters\n");
goto err;
}
ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "DHX", app_get0_propq());
if (ctx == NULL
|| EVP_PKEY_fromdata_init(ctx) <= 0
|| EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) {
BIO_printf(bio_err, "Error, failed to set DH parameters\n");
goto err;
}
err:
EVP_PKEY_CTX_free(ctx);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(tmpl);
BN_free(bn_p);
BN_free(bn_q);
BN_free(bn_g);
return pkey;
}
| 13,386 | 31.103118 | 86 |
c
|
openssl
|
openssl-master/apps/dsa.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/dsa.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/encoder.h>
#include <openssl/core_names.h>
#include <openssl/core_dispatch.h>
#ifndef OPENSSL_NO_RC4
# define DEFAULT_PVK_ENCR_STRENGTH 2
#else
# define DEFAULT_PVK_ENCR_STRENGTH 0
#endif
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENGINE,
/* Do not change the order here; see case statements below */
OPT_PVK_NONE, OPT_PVK_WEAK, OPT_PVK_STRONG,
OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_PUBIN,
OPT_PUBOUT, OPT_CIPHER, OPT_PASSIN, OPT_PASSOUT,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS dsa_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"", OPT_CIPHER, '-', "Any supported cipher"},
#ifndef OPENSSL_NO_RC4
{"pvk-strong", OPT_PVK_STRONG, '-', "Enable 'Strong' PVK encoding level (default)"},
{"pvk-weak", OPT_PVK_WEAK, '-', "Enable 'Weak' PVK encoding level"},
{"pvk-none", OPT_PVK_NONE, '-', "Don't enforce PVK encoding"},
#endif
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, 's', "Input key"},
{"inform", OPT_INFORM, 'f', "Input format (DER/PEM/PVK); has no effect"},
{"pubin", OPT_PUBIN, '-', "Expect a public key in input file"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'f', "Output format, DER PEM PVK"},
{"noout", OPT_NOOUT, '-', "Don't print key out"},
{"text", OPT_TEXT, '-', "Print the key in text"},
{"modulus", OPT_MODULUS, '-', "Print the DSA public value"},
{"pubout", OPT_PUBOUT, '-', "Output public key, not private"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
OPT_PROV_OPTIONS,
{NULL}
};
int dsa_main(int argc, char **argv)
{
BIO *out = NULL;
ENGINE *e = NULL;
EVP_PKEY *pkey = NULL;
EVP_CIPHER *enc = NULL;
char *infile = NULL, *outfile = NULL, *prog;
char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL;
OPTION_CHOICE o;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, noout = 0;
int modulus = 0, pubin = 0, pubout = 0, ret = 1;
int pvk_encr = DEFAULT_PVK_ENCR_STRENGTH;
int private = 0;
const char *output_type = NULL, *ciphername = NULL;
const char *output_structure = NULL;
int selection = 0;
OSSL_ENCODER_CTX *ectx = NULL;
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, dsa_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
ret = 0;
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(dsa_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_PVK_STRONG: /* pvk_encr:= 2 */
case OPT_PVK_WEAK: /* pvk_encr:= 1 */
case OPT_PVK_NONE: /* pvk_encr:= 0 */
#ifndef OPENSSL_NO_RC4
pvk_encr = (o - OPT_PVK_NONE);
#endif
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_MODULUS:
modulus = 1;
break;
case OPT_PUBIN:
pubin = 1;
break;
case OPT_PUBOUT:
pubout = 1;
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra args. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!opt_cipher(ciphername, &enc))
goto end;
private = !pubin && (!pubout || text);
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
BIO_printf(bio_err, "read DSA key\n");
if (pubin)
pkey = load_pubkey(infile, informat, 1, passin, e, "public key");
else
pkey = load_key(infile, informat, 1, passin, e, "private key");
if (pkey == NULL) {
BIO_printf(bio_err, "unable to load Key\n");
ERR_print_errors(bio_err);
goto end;
}
if (!EVP_PKEY_is_a(pkey, "DSA")) {
BIO_printf(bio_err, "Not a DSA key\n");
goto end;
}
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (text) {
assert(pubin || private);
if ((pubin && EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0)
|| (!pubin && EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)) {
perror(outfile);
ERR_print_errors(bio_err);
goto end;
}
}
if (modulus) {
BIGNUM *pub_key = NULL;
if (!EVP_PKEY_get_bn_param(pkey, "pub", &pub_key)) {
ERR_print_errors(bio_err);
goto end;
}
BIO_printf(out, "Public Key=");
BN_print(out, pub_key);
BIO_printf(out, "\n");
BN_free(pub_key);
}
if (noout) {
ret = 0;
goto end;
}
BIO_printf(bio_err, "writing DSA key\n");
if (outformat == FORMAT_ASN1) {
output_type = "DER";
} else if (outformat == FORMAT_PEM) {
output_type = "PEM";
} else if (outformat == FORMAT_MSBLOB) {
output_type = "MSBLOB";
} else if (outformat == FORMAT_PVK) {
if (pubin) {
BIO_printf(bio_err, "PVK form impossible with public key input\n");
goto end;
}
output_type = "PVK";
} else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
if (outformat == FORMAT_ASN1 || outformat == FORMAT_PEM) {
if (pubout || pubin)
output_structure = "SubjectPublicKeyInfo";
else
output_structure = "type-specific";
}
/* Select what you want in the output */
if (pubout || pubin) {
selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
} else {
assert(private);
selection = (OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS);
}
/* Perform the encoding */
ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, output_type,
output_structure, NULL);
if (OSSL_ENCODER_CTX_get_num_encoders(ectx) == 0) {
BIO_printf(bio_err, "%s format not supported\n", output_type);
goto end;
}
/* Passphrase setup */
if (enc != NULL)
OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL);
/* Default passphrase prompter */
if (enc != NULL || outformat == FORMAT_PVK) {
OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL);
if (passout != NULL)
/* When passout given, override the passphrase prompter */
OSSL_ENCODER_CTX_set_passphrase(ectx,
(const unsigned char *)passout,
strlen(passout));
}
/* PVK requires a bit more */
if (outformat == FORMAT_PVK) {
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_int("encrypt-level", &pvk_encr);
if (!OSSL_ENCODER_CTX_set_params(ectx, params)) {
BIO_printf(bio_err, "invalid PVK encryption level\n");
goto end;
}
}
if (!OSSL_ENCODER_to_bio(ectx, out)) {
BIO_printf(bio_err, "unable to write key\n");
goto end;
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
OSSL_ENCODER_CTX_free(ectx);
BIO_free_all(out);
EVP_PKEY_free(pkey);
EVP_CIPHER_free(enc);
release_engine(e);
OPENSSL_free(passin);
OPENSSL_free(passout);
return ret;
}
| 9,350 | 29.36039 | 88 |
c
|
openssl
|
openssl-master/apps/dsaparam.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/dsa.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
static int verbose = 0;
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT,
OPT_NOOUT, OPT_GENKEY, OPT_ENGINE, OPT_VERBOSE, OPT_QUIET,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS dsaparam_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits] [numqbits]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
{"text", OPT_TEXT, '-', "Print as text"},
{"noout", OPT_NOOUT, '-', "No output"},
{"verbose", OPT_VERBOSE, '-', "Verbose output"},
{"quiet", OPT_QUIET, '-', "Terse output"},
{"genkey", OPT_GENKEY, '-', "Generate a DSA key"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"numbits", 0, 0, "Number of bits if generating parameters or key (optional)"},
{"numqbits", 0, 0, "Number of bits in the subprime parameter q if generating parameters or key (optional)"},
{NULL}
};
int dsaparam_main(int argc, char **argv)
{
ENGINE *e = NULL;
BIO *out = NULL;
EVP_PKEY *params = NULL, *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
int numbits = -1, numqbits = -1, num = 0, genkey = 0;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, noout = 0;
int ret = 1, i, text = 0, private = 0;
char *infile = NULL, *outfile = NULL, *prog;
OPTION_CHOICE o;
prog = opt_init(argc, argv, dsaparam_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(dsaparam_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_TEXT:
text = 1;
break;
case OPT_GENKEY:
genkey = 1;
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_QUIET:
verbose = 0;
break;
}
}
/* Optional args are bitsize and q bitsize. */
argc = opt_num_rest();
argv = opt_rest();
if (argc == 2) {
if (!opt_int(argv[0], &num) || num < 0)
goto opthelp;
if (!opt_int(argv[1], &numqbits) || numqbits < 0)
goto opthelp;
} else if (argc == 1) {
if (!opt_int(argv[0], &num) || num < 0)
goto opthelp;
} else if (!opt_check_rest_arg(NULL)) {
goto opthelp;
}
if (!app_RAND_load())
goto end;
/* generate a key */
numbits = num;
private = genkey ? 1 : 0;
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "DSA", app_get0_propq());
if (ctx == NULL) {
BIO_printf(bio_err,
"Error, DSA parameter generation context allocation failed\n");
goto end;
}
if (numbits > 0) {
if (numbits > OPENSSL_DSA_MAX_MODULUS_BITS)
BIO_printf(bio_err,
"Warning: It is not recommended to use more than %d bit for DSA keys.\n"
" Your key size is %d! Larger key size may behave not as expected.\n",
OPENSSL_DSA_MAX_MODULUS_BITS, numbits);
EVP_PKEY_CTX_set_app_data(ctx, bio_err);
if (verbose) {
EVP_PKEY_CTX_set_cb(ctx, progress_cb);
BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n",
num);
BIO_printf(bio_err, "This could take some time\n");
}
if (EVP_PKEY_paramgen_init(ctx) <= 0) {
BIO_printf(bio_err,
"Error, DSA key generation paramgen init failed\n");
goto end;
}
if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num) <= 0) {
BIO_printf(bio_err,
"Error, DSA key generation setting bit length failed\n");
goto end;
}
if (numqbits > 0) {
if (EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, numqbits) <= 0) {
BIO_printf(bio_err,
"Error, DSA key generation setting subprime bit length failed\n");
goto end;
}
}
params = app_paramgen(ctx, "DSA");
} else {
params = load_keyparams(infile, informat, 1, "DSA", "DSA parameters");
}
if (params == NULL) {
/* Error message should already have been displayed */
goto end;
}
if (text) {
EVP_PKEY_print_params(out, params, 0, NULL);
}
if (outformat == FORMAT_ASN1 && genkey)
noout = 1;
if (!noout) {
if (outformat == FORMAT_ASN1)
i = i2d_KeyParams_bio(out, params);
else
i = PEM_write_bio_Parameters(out, params);
if (!i) {
BIO_printf(bio_err, "Error, unable to write DSA parameters\n");
goto end;
}
}
if (genkey) {
EVP_PKEY_CTX_free(ctx);
ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params,
app_get0_propq());
if (ctx == NULL) {
BIO_printf(bio_err,
"Error, DSA key generation context allocation failed\n");
goto end;
}
if (EVP_PKEY_keygen_init(ctx) <= 0) {
BIO_printf(bio_err,
"Error, unable to initialise for key generation\n");
goto end;
}
pkey = app_keygen(ctx, "DSA", numbits, verbose);
assert(private);
if (outformat == FORMAT_ASN1)
i = i2d_PrivateKey_bio(out, pkey);
else
i = PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, NULL);
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
BIO_free_all(out);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
EVP_PKEY_free(params);
release_engine(e);
return ret;
}
| 7,764 | 29.813492 | 112 |
c
|
openssl
|
openssl-master/apps/ec.c
|
/*
* Copyright 2002-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/opensslconf.h>
#include <openssl/evp.h>
#include <openssl/encoder.h>
#include <openssl/decoder.h>
#include <openssl/core_names.h>
#include <openssl/core_dispatch.h>
#include <openssl/params.h>
#include <openssl/err.h>
#include "apps.h"
#include "progs.h"
#include "ec_common.h"
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT,
OPT_NOOUT, OPT_TEXT, OPT_PARAM_OUT, OPT_PUBIN, OPT_PUBOUT,
OPT_PASSIN, OPT_PASSOUT, OPT_PARAM_ENC, OPT_CONV_FORM, OPT_CIPHER,
OPT_NO_PUBLIC, OPT_CHECK, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS ec_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, 's', "Input file"},
{"inform", OPT_INFORM, 'f', "Input format (DER/PEM/P12/ENGINE)"},
{"pubin", OPT_PUBIN, '-', "Expect a public key in input file"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"check", OPT_CHECK, '-', "check key consistency"},
{"", OPT_CIPHER, '-', "Any supported cipher"},
{"param_enc", OPT_PARAM_ENC, 's',
"Specifies the way the ec parameters are encoded"},
{"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
{"noout", OPT_NOOUT, '-', "Don't print key out"},
{"text", OPT_TEXT, '-', "Print the key"},
{"param_out", OPT_PARAM_OUT, '-', "Print the elliptic curve parameters"},
{"pubout", OPT_PUBOUT, '-', "Output public key, not private"},
{"no_public", OPT_NO_PUBLIC, '-', "exclude public key from private key"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
OPT_PROV_OPTIONS,
{NULL}
};
int ec_main(int argc, char **argv)
{
OSSL_ENCODER_CTX *ectx = NULL;
OSSL_DECODER_CTX *dctx = NULL;
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *eckey = NULL;
BIO *out = NULL;
ENGINE *e = NULL;
EVP_CIPHER *enc = NULL;
char *infile = NULL, *outfile = NULL, *ciphername = NULL, *prog;
char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL;
OPTION_CHOICE o;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, noout = 0;
int pubin = 0, pubout = 0, param_out = 0, ret = 1, private = 0;
int check = 0;
char *asn1_encoding = NULL;
char *point_format = NULL;
int no_public = 0;
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, ec_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(ec_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_PARAM_OUT:
param_out = 1;
break;
case OPT_PUBIN:
pubin = 1;
break;
case OPT_PUBOUT:
pubout = 1;
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_CONV_FORM:
point_format = opt_arg();
if (!opt_string(point_format, point_format_options))
goto opthelp;
break;
case OPT_PARAM_ENC:
asn1_encoding = opt_arg();
if (!opt_string(asn1_encoding, asn1_encoding_options))
goto opthelp;
break;
case OPT_NO_PUBLIC:
no_public = 1;
break;
case OPT_CHECK:
check = 1;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!opt_cipher(ciphername, &enc))
goto opthelp;
private = !pubin && (text || (!param_out && !pubout));
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
BIO_printf(bio_err, "read EC key\n");
if (pubin)
eckey = load_pubkey(infile, informat, 1, passin, e, "public key");
else
eckey = load_key(infile, informat, 1, passin, e, "private key");
if (eckey == NULL) {
BIO_printf(bio_err, "unable to load Key\n");
goto end;
}
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (point_format
&& !EVP_PKEY_set_utf8_string_param(
eckey, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
point_format)) {
BIO_printf(bio_err, "unable to set point conversion format\n");
goto end;
}
if (asn1_encoding != NULL
&& !EVP_PKEY_set_utf8_string_param(
eckey, OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding)) {
BIO_printf(bio_err, "unable to set asn1 encoding format\n");
goto end;
}
if (no_public) {
if (!EVP_PKEY_set_int_param(eckey, OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, 0)) {
BIO_printf(bio_err, "unable to disable public key encoding\n");
goto end;
}
} else {
if (!EVP_PKEY_set_int_param(eckey, OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, 1)) {
BIO_printf(bio_err, "unable to enable public key encoding\n");
goto end;
}
}
if (text) {
assert(pubin || private);
if ((pubin && EVP_PKEY_print_public(out, eckey, 0, NULL) <= 0)
|| (!pubin && EVP_PKEY_print_private(out, eckey, 0, NULL) <= 0)) {
BIO_printf(bio_err, "unable to print EC key\n");
goto end;
}
}
if (check) {
pctx = EVP_PKEY_CTX_new_from_pkey(NULL, eckey, NULL);
if (pctx == NULL) {
BIO_printf(bio_err, "unable to check EC key\n");
goto end;
}
if (EVP_PKEY_check(pctx) <= 0)
BIO_printf(bio_err, "EC Key Invalid!\n");
else
BIO_printf(bio_err, "EC Key valid.\n");
ERR_print_errors(bio_err);
}
if (!noout) {
int selection;
const char *output_type = outformat == FORMAT_ASN1 ? "DER" : "PEM";
const char *output_structure = "type-specific";
BIO_printf(bio_err, "writing EC key\n");
if (param_out) {
selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
} else if (pubin || pubout) {
selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
| OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
output_structure = "SubjectPublicKeyInfo";
} else {
selection = OSSL_KEYMGMT_SELECT_ALL;
assert(private);
}
ectx = OSSL_ENCODER_CTX_new_for_pkey(eckey, selection,
output_type, output_structure,
NULL);
if (enc != NULL) {
OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL);
/* Default passphrase prompter */
OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL);
if (passout != NULL)
/* When passout given, override the passphrase prompter */
OSSL_ENCODER_CTX_set_passphrase(ectx,
(const unsigned char *)passout,
strlen(passout));
}
if (!OSSL_ENCODER_to_bio(ectx, out)) {
BIO_printf(bio_err, "unable to write EC key\n");
goto end;
}
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
BIO_free_all(out);
EVP_PKEY_free(eckey);
EVP_CIPHER_free(enc);
OSSL_ENCODER_CTX_free(ectx);
OSSL_DECODER_CTX_free(dctx);
EVP_PKEY_CTX_free(pctx);
release_engine(e);
if (passin != NULL)
OPENSSL_clear_free(passin, strlen(passin));
if (passout != NULL)
OPENSSL_clear_free(passout, strlen(passout));
return ret;
}
| 9,406 | 31.32646 | 83 |
c
|
openssl
|
openssl-master/apps/ecparam.c
|
/*
* Copyright 2002-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/opensslconf.h>
#include <openssl/evp.h>
#include <openssl/encoder.h>
#include <openssl/decoder.h>
#include <openssl/core_names.h>
#include <openssl/core_dispatch.h>
#include <openssl/params.h>
#include <openssl/err.h>
#include "apps.h"
#include "progs.h"
#include "ec_common.h"
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT,
OPT_CHECK, OPT_LIST_CURVES, OPT_NO_SEED, OPT_NOOUT, OPT_NAME,
OPT_CONV_FORM, OPT_PARAM_ENC, OPT_GENKEY, OPT_ENGINE, OPT_CHECK_NAMED,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS ecparam_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"list_curves", OPT_LIST_CURVES, '-',
"Prints a list of all curve 'short names'"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"genkey", OPT_GENKEY, '-', "Generate ec key"},
{"in", OPT_IN, '<', "Input file - default stdin"},
{"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"},
{"out", OPT_OUT, '>', "Output file - default stdout"},
{"outform", OPT_OUTFORM, 'F', "Output format - default PEM"},
OPT_SECTION("Output"),
{"text", OPT_TEXT, '-', "Print the ec parameters in text form"},
{"noout", OPT_NOOUT, '-', "Do not print the ec parameter"},
{"param_enc", OPT_PARAM_ENC, 's',
"Specifies the way the ec parameters are encoded"},
OPT_SECTION("Parameter"),
{"check", OPT_CHECK, '-', "Validate the ec parameters"},
{"check_named", OPT_CHECK_NAMED, '-',
"Check that named EC curve parameters have not been modified"},
{"no_seed", OPT_NO_SEED, '-',
"If 'explicit' parameters are chosen do not use the seed"},
{"name", OPT_NAME, 's',
"Use the ec parameters with specified 'short name'"},
{"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
{NULL}
};
static int list_builtin_curves(BIO *out)
{
int ret = 0;
EC_builtin_curve *curves = NULL;
size_t n, crv_len = EC_get_builtin_curves(NULL, 0);
curves = app_malloc((int)sizeof(*curves) * crv_len, "list curves");
if (!EC_get_builtin_curves(curves, crv_len))
goto end;
for (n = 0; n < crv_len; n++) {
const char *comment = curves[n].comment;
const char *sname = OBJ_nid2sn(curves[n].nid);
if (comment == NULL)
comment = "CURVE DESCRIPTION NOT AVAILABLE";
if (sname == NULL)
sname = "";
BIO_printf(out, " %-10s: ", sname);
BIO_printf(out, "%s\n", comment);
}
ret = 1;
end:
OPENSSL_free(curves);
return ret;
}
int ecparam_main(int argc, char **argv)
{
EVP_PKEY_CTX *gctx_params = NULL, *gctx_key = NULL, *pctx = NULL;
EVP_PKEY *params_key = NULL, *key = NULL;
OSSL_ENCODER_CTX *ectx_key = NULL, *ectx_params = NULL;
OSSL_DECODER_CTX *dctx_params = NULL;
ENGINE *e = NULL;
BIO *out = NULL;
char *curve_name = NULL;
char *asn1_encoding = NULL;
char *point_format = NULL;
char *infile = NULL, *outfile = NULL, *prog;
OPTION_CHOICE o;
int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0;
int ret = 1, private = 0;
int no_seed = 0, check = 0, check_named = 0, text = 0, genkey = 0;
int list_curves = 0;
prog = opt_init(argc, argv, ecparam_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(ecparam_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_TEXT:
text = 1;
break;
case OPT_CHECK:
check = 1;
break;
case OPT_CHECK_NAMED:
check_named = 1;
break;
case OPT_LIST_CURVES:
list_curves = 1;
break;
case OPT_NO_SEED:
no_seed = 1;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_NAME:
curve_name = opt_arg();
break;
case OPT_CONV_FORM:
point_format = opt_arg();
if (!opt_string(point_format, point_format_options))
goto opthelp;
break;
case OPT_PARAM_ENC:
asn1_encoding = opt_arg();
if (!opt_string(asn1_encoding, asn1_encoding_options))
goto opthelp;
break;
case OPT_GENKEY:
genkey = 1;
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
}
}
/* No extra args. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!app_RAND_load())
goto end;
private = genkey ? 1 : 0;
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (list_curves) {
if (list_builtin_curves(out))
ret = 0;
goto end;
}
if (curve_name != NULL) {
OSSL_PARAM params[4];
OSSL_PARAM *p = params;
if (strcmp(curve_name, "secp192r1") == 0) {
BIO_printf(bio_err,
"using curve name prime192v1 instead of secp192r1\n");
curve_name = SN_X9_62_prime192v1;
} else if (strcmp(curve_name, "secp256r1") == 0) {
BIO_printf(bio_err,
"using curve name prime256v1 instead of secp256r1\n");
curve_name = SN_X9_62_prime256v1;
}
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
curve_name, 0);
if (asn1_encoding != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING,
asn1_encoding, 0);
if (point_format != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(
OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
point_format, 0);
*p = OSSL_PARAM_construct_end();
if (OPENSSL_strcasecmp(curve_name, "SM2") == 0)
gctx_params = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "sm2",
app_get0_propq());
else
gctx_params = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "ec",
app_get0_propq());
if (gctx_params == NULL
|| EVP_PKEY_keygen_init(gctx_params) <= 0
|| EVP_PKEY_CTX_set_params(gctx_params, params) <= 0
|| EVP_PKEY_keygen(gctx_params, ¶ms_key) <= 0) {
BIO_printf(bio_err, "unable to generate key\n");
goto end;
}
} else {
params_key = load_keyparams_suppress(infile, informat, 1, "EC",
"EC parameters", 1);
if (params_key == NULL)
params_key = load_keyparams_suppress(infile, informat, 1, "SM2",
"SM2 parameters", 1);
if (params_key == NULL) {
BIO_printf(bio_err, "Unable to load parameters from %s\n", infile);
goto end;
}
if (point_format
&& !EVP_PKEY_set_utf8_string_param(
params_key, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
point_format)) {
BIO_printf(bio_err, "unable to set point conversion format\n");
goto end;
}
if (asn1_encoding != NULL
&& !EVP_PKEY_set_utf8_string_param(
params_key, OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding)) {
BIO_printf(bio_err, "unable to set asn1 encoding format\n");
goto end;
}
}
if (no_seed
&& !EVP_PKEY_set_octet_string_param(params_key, OSSL_PKEY_PARAM_EC_SEED,
NULL, 0)) {
BIO_printf(bio_err, "unable to clear seed\n");
goto end;
}
if (text
&& !EVP_PKEY_print_params(out, params_key, 0, NULL)) {
BIO_printf(bio_err, "unable to print params\n");
goto end;
}
if (check || check_named) {
BIO_printf(bio_err, "checking elliptic curve parameters: ");
if (check_named
&& !EVP_PKEY_set_utf8_string_param(params_key,
OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE,
OSSL_PKEY_EC_GROUP_CHECK_NAMED)) {
BIO_printf(bio_err, "unable to set check_type\n");
goto end;
}
pctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params_key,
app_get0_propq());
if (pctx == NULL || EVP_PKEY_param_check(pctx) <= 0) {
BIO_printf(bio_err, "failed\n");
goto end;
}
BIO_printf(bio_err, "ok\n");
}
if (outformat == FORMAT_ASN1 && genkey)
noout = 1;
if (!noout) {
ectx_params = OSSL_ENCODER_CTX_new_for_pkey(
params_key, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL);
if (!OSSL_ENCODER_to_bio(ectx_params, out)) {
BIO_printf(bio_err, "unable to write elliptic curve parameters\n");
goto end;
}
}
if (genkey) {
/*
* NOTE: EC keygen does not normally need to pass in the param_key
* for named curves. This can be achieved using:
* gctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL);
* EVP_PKEY_keygen_init(gctx);
* EVP_PKEY_CTX_set_group_name(gctx, curvename);
* EVP_PKEY_keygen(gctx, &key) <= 0)
*/
gctx_key = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params_key,
app_get0_propq());
if (EVP_PKEY_keygen_init(gctx_key) <= 0
|| EVP_PKEY_keygen(gctx_key, &key) <= 0) {
BIO_printf(bio_err, "unable to generate key\n");
goto end;
}
assert(private);
ectx_key = OSSL_ENCODER_CTX_new_for_pkey(
key, OSSL_KEYMGMT_SELECT_ALL,
outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL);
if (!OSSL_ENCODER_to_bio(ectx_key, out)) {
BIO_printf(bio_err, "unable to write elliptic "
"curve parameters\n");
goto end;
}
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
release_engine(e);
EVP_PKEY_free(params_key);
EVP_PKEY_free(key);
EVP_PKEY_CTX_free(pctx);
EVP_PKEY_CTX_free(gctx_params);
EVP_PKEY_CTX_free(gctx_key);
OSSL_DECODER_CTX_free(dctx_params);
OSSL_ENCODER_CTX_free(ectx_params);
OSSL_ENCODER_CTX_free(ectx_key);
BIO_free_all(out);
return ret;
}
| 12,185 | 32.85 | 80 |
c
|
openssl
|
openssl-master/apps/enc.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/rand.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_COMP
# include <openssl/comp.h>
#endif
#include <ctype.h>
#undef SIZE
#undef BSIZE
#define SIZE (512)
#define BSIZE (8*1024)
#define PBKDF2_ITER_DEFAULT 10000
#define STR(a) XSTR(a)
#define XSTR(a) #a
static int set_hex(const char *in, unsigned char *out, int size);
static void show_ciphers(const OBJ_NAME *name, void *bio_);
struct doall_enc_ciphers {
BIO *bio;
int n;
};
typedef enum OPTION_choice {
OPT_COMMON,
OPT_LIST,
OPT_E, OPT_IN, OPT_OUT, OPT_PASS, OPT_ENGINE, OPT_D, OPT_P, OPT_V,
OPT_NOPAD, OPT_SALT, OPT_NOSALT, OPT_DEBUG, OPT_UPPER_P, OPT_UPPER_A,
OPT_A, OPT_Z, OPT_BUFSIZE, OPT_K, OPT_KFILE, OPT_UPPER_K, OPT_NONE,
OPT_UPPER_S, OPT_IV, OPT_MD, OPT_ITER, OPT_PBKDF2, OPT_CIPHER,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS enc_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"list", OPT_LIST, '-', "List ciphers"},
#ifndef OPENSSL_NO_DEPRECATED_3_0
{"ciphers", OPT_LIST, '-', "Alias for -list"},
#endif
{"e", OPT_E, '-', "Encrypt"},
{"d", OPT_D, '-', "Decrypt"},
{"p", OPT_P, '-', "Print the iv/key"},
{"P", OPT_UPPER_P, '-', "Print the iv/key and exit"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"k", OPT_K, 's', "Passphrase"},
{"kfile", OPT_KFILE, '<', "Read passphrase from file"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"pass", OPT_PASS, 's', "Passphrase source"},
{"v", OPT_V, '-', "Verbose output"},
{"a", OPT_A, '-', "Base64 encode/decode, depending on encryption flag"},
{"base64", OPT_A, '-', "Same as option -a"},
{"A", OPT_UPPER_A, '-',
"Used with -[base64|a] to specify base64 buffer as a single line"},
OPT_SECTION("Encryption"),
{"nopad", OPT_NOPAD, '-', "Disable standard block padding"},
{"salt", OPT_SALT, '-', "Use salt in the KDF (default)"},
{"nosalt", OPT_NOSALT, '-', "Do not use salt in the KDF"},
{"debug", OPT_DEBUG, '-', "Print debug info"},
{"bufsize", OPT_BUFSIZE, 's', "Buffer size"},
{"K", OPT_UPPER_K, 's', "Raw key, in hex"},
{"S", OPT_UPPER_S, 's', "Salt, in hex"},
{"iv", OPT_IV, 's', "IV in hex"},
{"md", OPT_MD, 's', "Use specified digest to create a key from the passphrase"},
{"iter", OPT_ITER, 'p',
"Specify the iteration count and force the use of PBKDF2"},
{OPT_MORE_STR, 0, 0, "Default: " STR(PBKDF2_ITER_DEFAULT)},
{"pbkdf2", OPT_PBKDF2, '-',
"Use password-based key derivation function 2 (PBKDF2)"},
{OPT_MORE_STR, 0, 0,
"Use -iter to change the iteration count from " STR(PBKDF2_ITER_DEFAULT)},
{"none", OPT_NONE, '-', "Don't encrypt"},
#ifndef OPENSSL_NO_ZLIB
{"z", OPT_Z, '-', "Compress or decompress encrypted data using zlib"},
#endif
{"", OPT_CIPHER, '-', "Any supported cipher"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
{NULL}
};
int enc_main(int argc, char **argv)
{
static char buf[128];
static const char magic[] = "Salted__";
ENGINE *e = NULL;
BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio =
NULL, *wbio = NULL;
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *cipher = NULL;
EVP_MD *dgst = NULL;
const char *digestname = NULL;
char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p;
char *infile = NULL, *outfile = NULL, *prog;
char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL;
const char *ciphername = NULL;
char mbuf[sizeof(magic) - 1];
OPTION_CHOICE o;
int bsize = BSIZE, verbose = 0, debug = 0, olb64 = 0, nosalt = 0;
int enc = 1, printkey = 0, i, k;
int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY;
int ret = 1, inl, nopad = 0;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
unsigned char *buff = NULL, salt[PKCS5_SALT_LEN];
int pbkdf2 = 0;
int iter = 0;
long n;
int streamable = 1;
int wrap = 0;
struct doall_enc_ciphers dec;
#ifndef OPENSSL_NO_ZLIB
int do_zlib = 0;
BIO *bzl = NULL;
#endif
int do_brotli = 0;
BIO *bbrot = NULL;
int do_zstd = 0;
BIO *bzstd = NULL;
/* first check the command name */
if (strcmp(argv[0], "base64") == 0)
base64 = 1;
#ifndef OPENSSL_NO_ZLIB
else if (strcmp(argv[0], "zlib") == 0)
do_zlib = 1;
#endif
#ifndef OPENSSL_NO_BROTLI
else if (strcmp(argv[0], "brotli") == 0)
do_brotli = 1;
#endif
#ifndef OPENSSL_NO_ZSTD
else if (strcmp(argv[0], "zstd") == 0)
do_zstd = 1;
#endif
else if (strcmp(argv[0], "enc") != 0)
ciphername = argv[0];
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, enc_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(enc_options);
ret = 0;
goto end;
case OPT_LIST:
BIO_printf(bio_out, "Supported ciphers:\n");
dec.bio = bio_out;
dec.n = 0;
OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
show_ciphers, &dec);
BIO_printf(bio_out, "\n");
ret = 0;
goto end;
case OPT_E:
enc = 1;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PASS:
passarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_D:
enc = 0;
break;
case OPT_P:
printkey = 1;
break;
case OPT_V:
verbose = 1;
break;
case OPT_NOPAD:
nopad = 1;
break;
case OPT_SALT:
nosalt = 0;
break;
case OPT_NOSALT:
nosalt = 1;
break;
case OPT_DEBUG:
debug = 1;
break;
case OPT_UPPER_P:
printkey = 2;
break;
case OPT_UPPER_A:
olb64 = 1;
break;
case OPT_A:
base64 = 1;
break;
case OPT_Z:
#ifndef OPENSSL_NO_ZLIB
do_zlib = 1;
#endif
break;
case OPT_BUFSIZE:
p = opt_arg();
i = (int)strlen(p) - 1;
k = i >= 1 && p[i] == 'k';
if (k)
p[i] = '\0';
if (!opt_long(opt_arg(), &n)
|| n < 0 || (k && n >= LONG_MAX / 1024))
goto opthelp;
if (k)
n *= 1024;
bsize = (int)n;
break;
case OPT_K:
str = opt_arg();
break;
case OPT_KFILE:
in = bio_open_default(opt_arg(), 'r', FORMAT_TEXT);
if (in == NULL)
goto opthelp;
i = BIO_gets(in, buf, sizeof(buf));
BIO_free(in);
in = NULL;
if (i <= 0) {
BIO_printf(bio_err,
"%s Can't read key from %s\n", prog, opt_arg());
goto opthelp;
}
while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n'))
buf[i] = '\0';
if (i <= 0) {
BIO_printf(bio_err, "%s: zero length password\n", prog);
goto opthelp;
}
str = buf;
break;
case OPT_UPPER_K:
hkey = opt_arg();
break;
case OPT_UPPER_S:
hsalt = opt_arg();
break;
case OPT_IV:
hiv = opt_arg();
break;
case OPT_MD:
digestname = opt_arg();
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_ITER:
iter = opt_int_arg();
pbkdf2 = 1;
break;
case OPT_PBKDF2:
pbkdf2 = 1;
if (iter == 0) /* do not overwrite a chosen value */
iter = PBKDF2_ITER_DEFAULT;
break;
case OPT_NONE:
cipher = NULL;
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!app_RAND_load())
goto end;
/* Get the cipher name, either from progname (if set) or flag. */
if (!opt_cipher(ciphername, &cipher))
goto opthelp;
if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_WRAP_MODE)) {
wrap = 1;
streamable = 0;
}
if (digestname != NULL) {
if (!opt_md(digestname, &dgst))
goto opthelp;
}
if (dgst == NULL)
dgst = (EVP_MD *)EVP_sha256();
if (iter == 0)
iter = 1;
/* It must be large enough for a base64 encoded line */
if (base64 && bsize < 80)
bsize = 80;
if (verbose)
BIO_printf(bio_err, "bufsize=%d\n", bsize);
#ifndef OPENSSL_NO_ZLIB
if (do_zlib)
base64 = 0;
#endif
if (do_brotli)
base64 = 0;
if (do_zstd)
base64 = 0;
if (base64) {
if (enc)
outformat = FORMAT_BASE64;
else
informat = FORMAT_BASE64;
}
strbuf = app_malloc(SIZE, "strbuf");
buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer");
if (infile == NULL) {
if (!streamable && printkey != 2) { /* if just print key and exit, it's ok */
BIO_printf(bio_err, "Unstreamable cipher mode\n");
goto end;
}
in = dup_bio_in(informat);
} else {
in = bio_open_default(infile, 'r', informat);
}
if (in == NULL)
goto end;
if (str == NULL && passarg != NULL) {
if (!app_passwd(passarg, NULL, &pass, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
str = pass;
}
if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) {
if (1) {
#ifndef OPENSSL_NO_UI_CONSOLE
for (;;) {
char prompt[200];
BIO_snprintf(prompt, sizeof(prompt), "enter %s %s password:",
EVP_CIPHER_get0_name(cipher),
(enc) ? "encryption" : "decryption");
strbuf[0] = '\0';
i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc);
if (i == 0) {
if (strbuf[0] == '\0') {
ret = 1;
goto end;
}
str = strbuf;
break;
}
if (i < 0) {
BIO_printf(bio_err, "bad password read\n");
goto end;
}
}
} else {
#endif
BIO_printf(bio_err, "password required\n");
goto end;
}
}
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
if (debug) {
BIO_set_callback_ex(in, BIO_debug_callback_ex);
BIO_set_callback_ex(out, BIO_debug_callback_ex);
BIO_set_callback_arg(in, (char *)bio_err);
BIO_set_callback_arg(out, (char *)bio_err);
}
rbio = in;
wbio = out;
#ifndef OPENSSL_NO_COMP
# ifndef OPENSSL_NO_ZLIB
if (do_zlib) {
if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
goto end;
if (debug) {
BIO_set_callback_ex(bzl, BIO_debug_callback_ex);
BIO_set_callback_arg(bzl, (char *)bio_err);
}
if (enc)
wbio = BIO_push(bzl, wbio);
else
rbio = BIO_push(bzl, rbio);
}
# endif
if (do_brotli) {
if ((bbrot = BIO_new(BIO_f_brotli())) == NULL)
goto end;
if (debug) {
BIO_set_callback_ex(bbrot, BIO_debug_callback_ex);
BIO_set_callback_arg(bbrot, (char *)bio_err);
}
if (enc)
wbio = BIO_push(bbrot, wbio);
else
rbio = BIO_push(bbrot, rbio);
}
if (do_zstd) {
if ((bzstd = BIO_new(BIO_f_zstd())) == NULL)
goto end;
if (debug) {
BIO_set_callback_ex(bzstd, BIO_debug_callback_ex);
BIO_set_callback_arg(bzstd, (char *)bio_err);
}
if (enc)
wbio = BIO_push(bzstd, wbio);
else
rbio = BIO_push(bzstd, rbio);
}
#endif
if (base64) {
if ((b64 = BIO_new(BIO_f_base64())) == NULL)
goto end;
if (debug) {
BIO_set_callback_ex(b64, BIO_debug_callback_ex);
BIO_set_callback_arg(b64, (char *)bio_err);
}
if (olb64)
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
if (enc)
wbio = BIO_push(b64, wbio);
else
rbio = BIO_push(b64, rbio);
}
if (cipher != NULL) {
if (str != NULL) { /* a passphrase is available */
/*
* Salt handling: if encrypting generate a salt if not supplied,
* and write to output BIO. If decrypting use salt from input BIO
* if not given with args
*/
unsigned char *sptr;
size_t str_len = strlen(str);
if (nosalt) {
sptr = NULL;
} else {
if (hsalt != NULL && !set_hex(hsalt, salt, sizeof(salt))) {
BIO_printf(bio_err, "invalid hex salt value\n");
goto end;
}
if (enc) { /* encryption */
if (hsalt == NULL) {
if (RAND_bytes(salt, sizeof(salt)) <= 0) {
BIO_printf(bio_err, "RAND_bytes failed\n");
goto end;
}
/*
* If -P option then don't bother writing.
* If salt is given, shouldn't either ?
*/
if ((printkey != 2)
&& (BIO_write(wbio, magic,
sizeof(magic) - 1) != sizeof(magic) - 1
|| BIO_write(wbio,
(char *)salt,
sizeof(salt)) != sizeof(salt))) {
BIO_printf(bio_err, "error writing output file\n");
goto end;
}
}
} else { /* decryption */
if (hsalt == NULL) {
if (BIO_read(rbio, mbuf, sizeof(mbuf)) != sizeof(mbuf)) {
BIO_printf(bio_err, "error reading input file\n");
goto end;
}
if (memcmp(mbuf, magic, sizeof(mbuf)) == 0) { /* file IS salted */
if (BIO_read(rbio, salt,
sizeof(salt)) != sizeof(salt)) {
BIO_printf(bio_err, "error reading input file\n");
goto end;
}
} else { /* file is NOT salted, NO salt available */
BIO_printf(bio_err, "bad magic number\n");
goto end;
}
}
}
sptr = salt;
}
if (pbkdf2 == 1) {
/*
* derive key and default iv
* concatenated into a temporary buffer
*/
unsigned char tmpkeyiv[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH];
int iklen = EVP_CIPHER_get_key_length(cipher);
int ivlen = EVP_CIPHER_get_iv_length(cipher);
/* not needed if HASH_UPDATE() is fixed : */
int islen = (sptr != NULL ? sizeof(salt) : 0);
if (!PKCS5_PBKDF2_HMAC(str, str_len, sptr, islen,
iter, dgst, iklen+ivlen, tmpkeyiv)) {
BIO_printf(bio_err, "PKCS5_PBKDF2_HMAC failed\n");
goto end;
}
/* split and move data back to global buffer */
memcpy(key, tmpkeyiv, iklen);
memcpy(iv, tmpkeyiv+iklen, ivlen);
} else {
BIO_printf(bio_err, "*** WARNING : "
"deprecated key derivation used.\n"
"Using -iter or -pbkdf2 would be better.\n");
if (!EVP_BytesToKey(cipher, dgst, sptr,
(unsigned char *)str, str_len,
1, key, iv)) {
BIO_printf(bio_err, "EVP_BytesToKey failed\n");
goto end;
}
}
/*
* zero the complete buffer or the string passed from the command
* line.
*/
if (str == strbuf)
OPENSSL_cleanse(str, SIZE);
else
OPENSSL_cleanse(str, str_len);
}
if (hiv != NULL) {
int siz = EVP_CIPHER_get_iv_length(cipher);
if (siz == 0) {
BIO_printf(bio_err, "warning: iv not used by this cipher\n");
} else if (!set_hex(hiv, iv, siz)) {
BIO_printf(bio_err, "invalid hex iv value\n");
goto end;
}
}
if ((hiv == NULL) && (str == NULL)
&& EVP_CIPHER_get_iv_length(cipher) != 0
&& wrap == 0) {
/*
* No IV was explicitly set and no IV was generated.
* Hence the IV is undefined, making correct decryption impossible.
*/
BIO_printf(bio_err, "iv undefined\n");
goto end;
}
if (hkey != NULL) {
if (!set_hex(hkey, key, EVP_CIPHER_get_key_length(cipher))) {
BIO_printf(bio_err, "invalid hex key value\n");
goto end;
}
/* wiping secret data as we no longer need it */
cleanse(hkey);
}
if ((benc = BIO_new(BIO_f_cipher())) == NULL)
goto end;
/*
* Since we may be changing parameters work on the encryption context
* rather than calling BIO_set_cipher().
*/
BIO_get_cipher_ctx(benc, &ctx);
if (wrap == 1)
EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
if (!EVP_CipherInit_ex(ctx, cipher, e, NULL, NULL, enc)) {
BIO_printf(bio_err, "Error setting cipher %s\n",
EVP_CIPHER_get0_name(cipher));
ERR_print_errors(bio_err);
goto end;
}
if (nopad)
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_CipherInit_ex(ctx, NULL, NULL, key,
(hiv == NULL && wrap == 1 ? NULL : iv), enc)) {
BIO_printf(bio_err, "Error setting cipher %s\n",
EVP_CIPHER_get0_name(cipher));
ERR_print_errors(bio_err);
goto end;
}
if (debug) {
BIO_set_callback_ex(benc, BIO_debug_callback_ex);
BIO_set_callback_arg(benc, (char *)bio_err);
}
if (printkey) {
if (!nosalt) {
printf("salt=");
for (i = 0; i < (int)sizeof(salt); i++)
printf("%02X", salt[i]);
printf("\n");
}
if (EVP_CIPHER_get_key_length(cipher) > 0) {
printf("key=");
for (i = 0; i < EVP_CIPHER_get_key_length(cipher); i++)
printf("%02X", key[i]);
printf("\n");
}
if (EVP_CIPHER_get_iv_length(cipher) > 0) {
printf("iv =");
for (i = 0; i < EVP_CIPHER_get_iv_length(cipher); i++)
printf("%02X", iv[i]);
printf("\n");
}
if (printkey == 2) {
ret = 0;
goto end;
}
}
}
/* Only encrypt/decrypt as we write the file */
if (benc != NULL)
wbio = BIO_push(benc, wbio);
while (BIO_pending(rbio) || !BIO_eof(rbio)) {
inl = BIO_read(rbio, (char *)buff, bsize);
if (inl <= 0)
break;
if (!streamable && !BIO_eof(rbio)) { /* do not output data */
BIO_printf(bio_err, "Unstreamable cipher mode\n");
goto end;
}
if (BIO_write(wbio, (char *)buff, inl) != inl) {
BIO_printf(bio_err, "error writing output file\n");
goto end;
}
if (!streamable)
break;
}
if (!BIO_flush(wbio)) {
BIO_printf(bio_err, "bad decrypt\n");
goto end;
}
ret = 0;
if (verbose) {
BIO_printf(bio_err, "bytes read : %8ju\n", BIO_number_read(in));
BIO_printf(bio_err, "bytes written: %8ju\n", BIO_number_written(out));
}
end:
ERR_print_errors(bio_err);
OPENSSL_free(strbuf);
OPENSSL_free(buff);
BIO_free(in);
BIO_free_all(out);
BIO_free(benc);
BIO_free(b64);
EVP_MD_free(dgst);
EVP_CIPHER_free(cipher);
#ifndef OPENSSL_NO_ZLIB
BIO_free(bzl);
#endif
BIO_free(bbrot);
BIO_free(bzstd);
release_engine(e);
OPENSSL_free(pass);
return ret;
}
static void show_ciphers(const OBJ_NAME *name, void *arg)
{
struct doall_enc_ciphers *dec = (struct doall_enc_ciphers *)arg;
const EVP_CIPHER *cipher;
if (!islower((unsigned char)*name->name))
return;
/* Filter out ciphers that we cannot use */
cipher = EVP_get_cipherbyname(name->name);
if (cipher == NULL
|| (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0
|| EVP_CIPHER_get_mode(cipher) == EVP_CIPH_XTS_MODE)
return;
BIO_printf(dec->bio, "-%-25s", name->name);
if (++dec->n == 3) {
BIO_printf(dec->bio, "\n");
dec->n = 0;
} else
BIO_printf(dec->bio, " ");
}
static int set_hex(const char *in, unsigned char *out, int size)
{
int i, n;
unsigned char j;
i = size * 2;
n = strlen(in);
if (n > i) {
BIO_printf(bio_err, "hex string is too long, ignoring excess\n");
n = i; /* ignore exceeding part */
} else if (n < i) {
BIO_printf(bio_err, "hex string is too short, padding with zero bytes to length\n");
}
memset(out, 0, size);
for (i = 0; i < n; i++) {
j = (unsigned char)*in++;
if (!isxdigit(j)) {
BIO_printf(bio_err, "non-hex digit\n");
return 0;
}
j = (unsigned char)OPENSSL_hexchar2int(j);
if (i & 1)
out[i / 2] |= j;
else
out[i / 2] = (j << 4);
}
return 1;
}
| 24,173 | 30.272962 | 92 |
c
|
openssl
|
openssl-master/apps/engine.c
|
/*
* Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/opensslconf.h>
#include "apps.h"
#include "progs.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/engine.h>
#include <openssl/ssl.h>
#include <openssl/store.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_C, OPT_T, OPT_TT, OPT_PRE, OPT_POST,
OPT_V = 100, OPT_VV, OPT_VVV, OPT_VVVV
} OPTION_CHOICE;
const OPTIONS engine_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] engine...\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"t", OPT_T, '-', "Check that specified engine is available"},
{"pre", OPT_PRE, 's', "Run command against the ENGINE before loading it"},
{"post", OPT_POST, 's', "Run command against the ENGINE after loading it"},
OPT_SECTION("Output"),
{"v", OPT_V, '-', "List 'control commands' For each specified engine"},
{"vv", OPT_VV, '-', "Also display each command's description"},
{"vvv", OPT_VVV, '-', "Also add the input flags for each command"},
{"vvvv", OPT_VVVV, '-', "Also show internal input flags"},
{"c", OPT_C, '-', "List the capabilities of specified engine"},
{"tt", OPT_TT, '-', "Display error trace for unavailable engines"},
{OPT_MORE_STR, OPT_EOF, 1,
"Commands are like \"SO_PATH:/lib/libdriver.so\""},
OPT_PARAMETERS(),
{"engine", 0, 0, "ID of engine(s) to load"},
{NULL}
};
static int append_buf(char **buf, int *size, const char *s)
{
const int expand = 256;
int len = strlen(s) + 1;
char *p = *buf;
if (p == NULL) {
*size = ((len + expand - 1) / expand) * expand;
p = *buf = app_malloc(*size, "engine buffer");
} else {
const int blen = strlen(p);
if (blen > 0)
len += 2 + blen;
if (len > *size) {
*size = ((len + expand - 1) / expand) * expand;
p = OPENSSL_realloc(p, *size);
if (p == NULL) {
OPENSSL_free(*buf);
*buf = NULL;
return 0;
}
*buf = p;
}
if (blen > 0) {
p += blen;
*p++ = ',';
*p++ = ' ';
}
}
strcpy(p, s);
return 1;
}
static int util_flags(BIO *out, unsigned int flags, const char *indent)
{
int started = 0, err = 0;
/* Indent before displaying input flags */
BIO_printf(out, "%s%s(input flags): ", indent, indent);
if (flags == 0) {
BIO_printf(out, "<no flags>\n");
return 1;
}
/*
* If the object is internal, mark it in a way that shows instead of
* having it part of all the other flags, even if it really is.
*/
if (flags & ENGINE_CMD_FLAG_INTERNAL) {
BIO_printf(out, "[Internal] ");
}
if (flags & ENGINE_CMD_FLAG_NUMERIC) {
BIO_printf(out, "NUMERIC");
started = 1;
}
/*
* Now we check that no combinations of the mutually exclusive NUMERIC,
* STRING, and NO_INPUT flags have been used. Future flags that can be
* OR'd together with these would need to added after these to preserve
* the testing logic.
*/
if (flags & ENGINE_CMD_FLAG_STRING) {
if (started) {
BIO_printf(out, "|");
err = 1;
}
BIO_printf(out, "STRING");
started = 1;
}
if (flags & ENGINE_CMD_FLAG_NO_INPUT) {
if (started) {
BIO_printf(out, "|");
err = 1;
}
BIO_printf(out, "NO_INPUT");
started = 1;
}
/* Check for unknown flags */
flags = flags & ~ENGINE_CMD_FLAG_NUMERIC &
~ENGINE_CMD_FLAG_STRING &
~ENGINE_CMD_FLAG_NO_INPUT & ~ENGINE_CMD_FLAG_INTERNAL;
if (flags) {
if (started)
BIO_printf(out, "|");
BIO_printf(out, "<0x%04X>", flags);
}
if (err)
BIO_printf(out, " <illegal flags!>");
BIO_printf(out, "\n");
return 1;
}
static int util_verbose(ENGINE *e, int verbose, BIO *out, const char *indent)
{
static const int line_wrap = 78;
int num;
int ret = 0;
char *name = NULL;
char *desc = NULL;
int flags;
int xpos = 0;
STACK_OF(OPENSSL_STRING) *cmds = NULL;
if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) ||
((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE,
0, NULL, NULL)) <= 0)) {
return 1;
}
cmds = sk_OPENSSL_STRING_new_null();
if (cmds == NULL)
goto err;
do {
int len;
/* Get the command input flags */
if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num,
NULL, NULL)) < 0)
goto err;
if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) {
/* Get the command name */
if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num,
NULL, NULL)) <= 0)
goto err;
name = app_malloc(len + 1, "name buffer");
if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name,
NULL) <= 0)
goto err;
/* Get the command description */
if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num,
NULL, NULL)) < 0)
goto err;
if (len > 0) {
desc = app_malloc(len + 1, "description buffer");
if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc,
NULL) <= 0)
goto err;
}
/* Now decide on the output */
if (xpos == 0)
/* Do an indent */
xpos = BIO_puts(out, indent);
else
/* Otherwise prepend a ", " */
xpos += BIO_printf(out, ", ");
if (verbose == 1) {
/*
* We're just listing names, comma-delimited
*/
if ((xpos > (int)strlen(indent)) &&
(xpos + (int)strlen(name) > line_wrap)) {
BIO_printf(out, "\n");
xpos = BIO_puts(out, indent);
}
xpos += BIO_printf(out, "%s", name);
} else {
/* We're listing names plus descriptions */
BIO_printf(out, "%s: %s\n", name,
(desc == NULL) ? "<no description>" : desc);
/* ... and sometimes input flags */
if ((verbose >= 3) && !util_flags(out, flags, indent))
goto err;
xpos = 0;
}
}
OPENSSL_free(name);
name = NULL;
OPENSSL_free(desc);
desc = NULL;
/* Move to the next command */
num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE, num, NULL, NULL);
} while (num > 0);
if (xpos > 0)
BIO_printf(out, "\n");
ret = 1;
err:
sk_OPENSSL_STRING_free(cmds);
OPENSSL_free(name);
OPENSSL_free(desc);
return ret;
}
static void util_do_cmds(ENGINE *e, STACK_OF(OPENSSL_STRING) *cmds,
BIO *out, const char *indent)
{
int loop, res, num = sk_OPENSSL_STRING_num(cmds);
if (num < 0) {
BIO_printf(out, "[Error]: internal stack error\n");
return;
}
for (loop = 0; loop < num; loop++) {
char buf[256];
const char *cmd, *arg;
cmd = sk_OPENSSL_STRING_value(cmds, loop);
res = 1; /* assume success */
/* Check if this command has no ":arg" */
if ((arg = strstr(cmd, ":")) == NULL) {
if (!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0))
res = 0;
} else {
if ((int)(arg - cmd) > 254) {
BIO_printf(out, "[Error]: command name too long\n");
return;
}
memcpy(buf, cmd, (int)(arg - cmd));
buf[arg - cmd] = '\0';
arg++; /* Move past the ":" */
/* Call the command with the argument */
if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0))
res = 0;
}
if (res) {
BIO_printf(out, "[Success]: %s\n", cmd);
} else {
BIO_printf(out, "[Failure]: %s\n", cmd);
ERR_print_errors(out);
}
}
}
struct util_store_cap_data {
ENGINE *engine;
char **cap_buf;
int *cap_size;
int ok;
};
static void util_store_cap(const OSSL_STORE_LOADER *loader, void *arg)
{
struct util_store_cap_data *ctx = arg;
if (OSSL_STORE_LOADER_get0_engine(loader) == ctx->engine) {
char buf[256];
BIO_snprintf(buf, sizeof(buf), "STORE(%s)",
OSSL_STORE_LOADER_get0_scheme(loader));
if (!append_buf(ctx->cap_buf, ctx->cap_size, buf))
ctx->ok = 0;
}
}
int engine_main(int argc, char **argv)
{
int ret = 1, i;
int verbose = 0, list_cap = 0, test_avail = 0, test_avail_noise = 0;
ENGINE *e;
STACK_OF(OPENSSL_CSTRING) *engines = sk_OPENSSL_CSTRING_new_null();
STACK_OF(OPENSSL_STRING) *pre_cmds = sk_OPENSSL_STRING_new_null();
STACK_OF(OPENSSL_STRING) *post_cmds = sk_OPENSSL_STRING_new_null();
BIO *out;
const char *indent = " ";
OPTION_CHOICE o;
char *prog;
char *argv1;
out = dup_bio_out(FORMAT_TEXT);
if (engines == NULL || pre_cmds == NULL || post_cmds == NULL)
goto end;
/* Remember the original command name, parse/skip any leading engine
* names, and then setup to parse the rest of the line as flags. */
prog = argv[0];
while ((argv1 = argv[1]) != NULL && *argv1 != '-') {
sk_OPENSSL_CSTRING_push(engines, argv1);
argc--;
argv++;
}
argv[0] = prog;
opt_init(argc, argv, engine_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(engine_options);
ret = 0;
goto end;
case OPT_VVVV:
case OPT_VVV:
case OPT_VV:
case OPT_V:
/* Convert to an integer from one to four. */
i = (int)(o - OPT_V) + 1;
if (verbose < i)
verbose = i;
break;
case OPT_C:
list_cap = 1;
break;
case OPT_TT:
test_avail_noise++;
/* fall through */
case OPT_T:
test_avail++;
break;
case OPT_PRE:
sk_OPENSSL_STRING_push(pre_cmds, opt_arg());
break;
case OPT_POST:
sk_OPENSSL_STRING_push(post_cmds, opt_arg());
break;
}
}
/* Any remaining arguments are engine names. */
argc = opt_num_rest();
argv = opt_rest();
for ( ; *argv; argv++) {
if (**argv == '-') {
BIO_printf(bio_err, "%s: Cannot mix flags and engine names.\n",
prog);
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
}
sk_OPENSSL_CSTRING_push(engines, *argv);
}
if (sk_OPENSSL_CSTRING_num(engines) == 0) {
for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) {
sk_OPENSSL_CSTRING_push(engines, ENGINE_get_id(e));
}
}
ret = 0;
for (i = 0; i < sk_OPENSSL_CSTRING_num(engines); i++) {
const char *id = sk_OPENSSL_CSTRING_value(engines, i);
if ((e = ENGINE_by_id(id)) != NULL) {
const char *name = ENGINE_get_name(e);
/*
* Do "id" first, then "name". Easier to auto-parse.
*/
BIO_printf(out, "(%s) %s\n", id, name);
util_do_cmds(e, pre_cmds, out, indent);
if (strcmp(ENGINE_get_id(e), id) != 0) {
BIO_printf(out, "Loaded: (%s) %s\n",
ENGINE_get_id(e), ENGINE_get_name(e));
}
if (list_cap) {
int cap_size = 256;
char *cap_buf = NULL;
int k, n;
const int *nids;
ENGINE_CIPHERS_PTR fn_c;
ENGINE_DIGESTS_PTR fn_d;
ENGINE_PKEY_METHS_PTR fn_pk;
if (ENGINE_get_RSA(e) != NULL
&& !append_buf(&cap_buf, &cap_size, "RSA"))
goto end;
if (ENGINE_get_DSA(e) != NULL
&& !append_buf(&cap_buf, &cap_size, "DSA"))
goto end;
if (ENGINE_get_DH(e) != NULL
&& !append_buf(&cap_buf, &cap_size, "DH"))
goto end;
if (ENGINE_get_RAND(e) != NULL
&& !append_buf(&cap_buf, &cap_size, "RAND"))
goto end;
fn_c = ENGINE_get_ciphers(e);
if (fn_c == NULL)
goto skip_ciphers;
n = fn_c(e, NULL, &nids, 0);
for (k = 0; k < n; ++k)
if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
goto end;
skip_ciphers:
fn_d = ENGINE_get_digests(e);
if (fn_d == NULL)
goto skip_digests;
n = fn_d(e, NULL, &nids, 0);
for (k = 0; k < n; ++k)
if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
goto end;
skip_digests:
fn_pk = ENGINE_get_pkey_meths(e);
if (fn_pk == NULL)
goto skip_pmeths;
n = fn_pk(e, NULL, &nids, 0);
for (k = 0; k < n; ++k)
if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
goto end;
skip_pmeths:
{
struct util_store_cap_data store_ctx;
store_ctx.engine = e;
store_ctx.cap_buf = &cap_buf;
store_ctx.cap_size = &cap_size;
store_ctx.ok = 1;
OSSL_STORE_do_all_loaders(util_store_cap, &store_ctx);
if (!store_ctx.ok)
goto end;
}
if (cap_buf != NULL && (*cap_buf != '\0'))
BIO_printf(out, " [%s]\n", cap_buf);
OPENSSL_free(cap_buf);
}
if (test_avail) {
BIO_printf(out, "%s", indent);
if (ENGINE_init(e)) {
BIO_printf(out, "[ available ]\n");
util_do_cmds(e, post_cmds, out, indent);
ENGINE_finish(e);
} else {
BIO_printf(out, "[ unavailable ]\n");
if (test_avail_noise)
ERR_print_errors_fp(stdout);
ERR_clear_error();
}
}
if ((verbose > 0) && !util_verbose(e, verbose, out, indent))
goto end;
ENGINE_free(e);
} else {
ERR_print_errors(bio_err);
/* because exit codes above 127 have special meaning on Unix */
if (++ret > 127)
ret = 127;
}
}
end:
ERR_print_errors(bio_err);
sk_OPENSSL_CSTRING_free(engines);
sk_OPENSSL_STRING_free(pre_cmds);
sk_OPENSSL_STRING_free(post_cmds);
BIO_free_all(out);
return ret;
}
| 16,057 | 31.506073 | 79 |
c
|
openssl
|
openssl-master/apps/errstr.c
|
/*
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
typedef enum OPTION_choice {
OPT_ERR = -1, OPT_EOF = 0, OPT_HELP
} OPTION_CHOICE;
const OPTIONS errstr_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] errnum...\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_PARAMETERS(),
{"errnum", 0, 0, "Error number(s) to decode"},
{NULL}
};
int errstr_main(int argc, char **argv)
{
OPTION_CHOICE o;
char buf[256], *prog;
int ret = 1;
unsigned long l;
prog = opt_init(argc, argv, errstr_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(errstr_options);
ret = 0;
goto end;
}
}
/*
* We're not really an SSL application so this won't auto-init, but
* we're still interested in SSL error strings
*/
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
/* All remaining arg are error code. */
ret = 0;
for (argv = opt_rest(); *argv != NULL; argv++) {
if (sscanf(*argv, "%lx", &l) == 0) {
ret++;
} else {
ERR_error_string_n(l, buf, sizeof(buf));
BIO_printf(bio_out, "%s\n", buf);
}
}
end:
return ret;
}
| 1,945 | 24.946667 | 74 |
c
|
openssl
|
openssl-master/apps/fipsinstall.c
|
/*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/provider.h>
#include <openssl/params.h>
#include <openssl/fips_names.h>
#include <openssl/core_names.h>
#include <openssl/self_test.h>
#include <openssl/fipskey.h>
#include "apps.h"
#include "progs.h"
#define BUFSIZE 4096
/* Configuration file values */
#define VERSION_KEY "version"
#define VERSION_VAL "1"
#define INSTALL_STATUS_VAL "INSTALL_SELF_TEST_KATS_RUN"
static OSSL_CALLBACK self_test_events;
static char *self_test_corrupt_desc = NULL;
static char *self_test_corrupt_type = NULL;
static int self_test_log = 1;
static int quiet = 0;
typedef enum OPTION_choice {
OPT_COMMON,
OPT_IN, OPT_OUT, OPT_MODULE, OPT_PEDANTIC,
OPT_PROV_NAME, OPT_SECTION_NAME, OPT_MAC_NAME, OPT_MACOPT, OPT_VERIFY,
OPT_NO_LOG, OPT_CORRUPT_DESC, OPT_CORRUPT_TYPE, OPT_QUIET, OPT_CONFIG,
OPT_NO_CONDITIONAL_ERRORS,
OPT_NO_SECURITY_CHECKS,
OPT_TLS_PRF_EMS_CHECK,
OPT_DISALLOW_DRGB_TRUNC_DIGEST,
OPT_SELF_TEST_ONLOAD, OPT_SELF_TEST_ONINSTALL
} OPTION_CHOICE;
const OPTIONS fipsinstall_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"pedantic", OPT_PEDANTIC, '-', "Set options for strict FIPS compliance"},
{"verify", OPT_VERIFY, '-',
"Verify a config file instead of generating one"},
{"module", OPT_MODULE, '<', "File name of the provider module"},
{"provider_name", OPT_PROV_NAME, 's', "FIPS provider name"},
{"section_name", OPT_SECTION_NAME, 's',
"FIPS Provider config section name (optional)"},
{"no_conditional_errors", OPT_NO_CONDITIONAL_ERRORS, '-',
"Disable the ability of the fips module to enter an error state if"
" any conditional self tests fail"},
{"no_security_checks", OPT_NO_SECURITY_CHECKS, '-',
"Disable the run-time FIPS security checks in the module"},
{"self_test_onload", OPT_SELF_TEST_ONLOAD, '-',
"Forces self tests to always run on module load"},
{"self_test_oninstall", OPT_SELF_TEST_ONINSTALL, '-',
"Forces self tests to run once on module installation"},
{"ems_check", OPT_TLS_PRF_EMS_CHECK, '-',
"Enable the run-time FIPS check for EMS during TLS1_PRF"},
{"no_drbg_truncated_digests", OPT_DISALLOW_DRGB_TRUNC_DIGEST, '-',
"Disallow truncated digests with Hash and HMAC DRBGs"},
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input config file, used when verifying"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output config file, used when generating"},
{"mac_name", OPT_MAC_NAME, 's', "MAC name"},
{"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form."},
{OPT_MORE_STR, 0, 0, "See 'PARAMETER NAMES' in the EVP_MAC_ docs"},
{"noout", OPT_NO_LOG, '-', "Disable logging of self test events"},
{"corrupt_desc", OPT_CORRUPT_DESC, 's', "Corrupt a self test by description"},
{"corrupt_type", OPT_CORRUPT_TYPE, 's', "Corrupt a self test by type"},
{"config", OPT_CONFIG, '<', "The parent config to verify"},
{"quiet", OPT_QUIET, '-', "No messages, just exit status"},
{NULL}
};
typedef struct {
unsigned int self_test_onload : 1;
unsigned int conditional_errors : 1;
unsigned int security_checks : 1;
unsigned int tls_prf_ems_check : 1;
unsigned int drgb_no_trunc_dgst : 1;
} FIPS_OPTS;
/* Pedantic FIPS compliance */
static const FIPS_OPTS pedantic_opts = {
1, /* self_test_onload */
1, /* conditional_errors */
1, /* security_checks */
1, /* tls_prf_ems_check */
1, /* drgb_no_trunc_dgst */
};
/* Default FIPS settings for backward compatibility */
static FIPS_OPTS fips_opts = {
1, /* self_test_onload */
1, /* conditional_errors */
1, /* security_checks */
0, /* tls_prf_ems_check */
0, /* drgb_no_trunc_dgst */
};
static int check_non_pedantic_fips(int pedantic, const char *name)
{
if (pedantic) {
BIO_printf(bio_err, "Cannot specify -%s after -pedantic\n", name);
return 0;
}
return 1;
}
static int do_mac(EVP_MAC_CTX *ctx, unsigned char *tmp, BIO *in,
unsigned char *out, size_t *out_len)
{
int ret = 0;
int i;
size_t outsz = *out_len;
if (!EVP_MAC_init(ctx, NULL, 0, NULL))
goto err;
if (EVP_MAC_CTX_get_mac_size(ctx) > outsz)
goto end;
while ((i = BIO_read(in, (char *)tmp, BUFSIZE)) != 0) {
if (i < 0 || !EVP_MAC_update(ctx, tmp, i))
goto err;
}
end:
if (!EVP_MAC_final(ctx, out, out_len, outsz))
goto err;
ret = 1;
err:
return ret;
}
static int load_fips_prov_and_run_self_test(const char *prov_name)
{
int ret = 0;
OSSL_PROVIDER *prov = NULL;
OSSL_PARAM params[4], *p = params;
char *name = "", *vers = "", *build = "";
prov = OSSL_PROVIDER_load(NULL, prov_name);
if (prov == NULL) {
BIO_printf(bio_err, "Failed to load FIPS module\n");
goto end;
}
if (!quiet) {
*p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_NAME,
&name, sizeof(name));
*p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_VERSION,
&vers, sizeof(vers));
*p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_BUILDINFO,
&build, sizeof(build));
*p = OSSL_PARAM_construct_end();
if (!OSSL_PROVIDER_get_params(prov, params)) {
BIO_printf(bio_err, "Failed to query FIPS module parameters\n");
goto end;
}
if (OSSL_PARAM_modified(params))
BIO_printf(bio_err, "\t%-10s\t%s\n", "name:", name);
if (OSSL_PARAM_modified(params + 1))
BIO_printf(bio_err, "\t%-10s\t%s\n", "version:", vers);
if (OSSL_PARAM_modified(params + 2))
BIO_printf(bio_err, "\t%-10s\t%s\n", "build:", build);
}
ret = 1;
end:
OSSL_PROVIDER_unload(prov);
return ret;
}
static int print_mac(BIO *bio, const char *label, const unsigned char *mac,
size_t len)
{
int ret;
char *hexstr = NULL;
hexstr = OPENSSL_buf2hexstr(mac, (long)len);
if (hexstr == NULL)
return 0;
ret = BIO_printf(bio, "%s = %s\n", label, hexstr);
OPENSSL_free(hexstr);
return ret;
}
static int write_config_header(BIO *out, const char *prov_name,
const char *section)
{
return BIO_printf(out, "openssl_conf = openssl_init\n\n")
&& BIO_printf(out, "[openssl_init]\n")
&& BIO_printf(out, "providers = provider_section\n\n")
&& BIO_printf(out, "[provider_section]\n")
&& BIO_printf(out, "%s = %s\n\n", prov_name, section);
}
/*
* Outputs a fips related config file that contains entries for the fips
* module checksum, installation indicator checksum and the options
* conditional_errors and security_checks.
*
* Returns 1 if the config file is written otherwise it returns 0 on error.
*/
static int write_config_fips_section(BIO *out, const char *section,
unsigned char *module_mac,
size_t module_mac_len,
const FIPS_OPTS *opts,
unsigned char *install_mac,
size_t install_mac_len)
{
int ret = 0;
if (BIO_printf(out, "[%s]\n", section) <= 0
|| BIO_printf(out, "activate = 1\n") <= 0
|| BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_INSTALL_VERSION,
VERSION_VAL) <= 0
|| BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_CONDITIONAL_ERRORS,
opts->conditional_errors ? "1" : "0") <= 0
|| BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_SECURITY_CHECKS,
opts->security_checks ? "1" : "0") <= 0
|| BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_TLS1_PRF_EMS_CHECK,
opts->tls_prf_ems_check ? "1" : "0") <= 0
|| BIO_printf(out, "%s = %s\n", OSSL_PROV_PARAM_DRBG_TRUNC_DIGEST,
opts->drgb_no_trunc_dgst ? "1" : "0") <= 0
|| !print_mac(out, OSSL_PROV_FIPS_PARAM_MODULE_MAC, module_mac,
module_mac_len))
goto end;
if (install_mac != NULL && install_mac_len > 0) {
if (!print_mac(out, OSSL_PROV_FIPS_PARAM_INSTALL_MAC, install_mac,
install_mac_len)
|| BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_INSTALL_STATUS,
INSTALL_STATUS_VAL) <= 0)
goto end;
}
ret = 1;
end:
return ret;
}
static CONF *generate_config_and_load(const char *prov_name,
const char *section,
unsigned char *module_mac,
size_t module_mac_len,
const FIPS_OPTS *opts)
{
BIO *mem_bio = NULL;
CONF *conf = NULL;
mem_bio = BIO_new(BIO_s_mem());
if (mem_bio == NULL)
return 0;
if (!write_config_header(mem_bio, prov_name, section)
|| !write_config_fips_section(mem_bio, section,
module_mac, module_mac_len,
opts, NULL, 0))
goto end;
conf = app_load_config_bio(mem_bio, NULL);
if (conf == NULL)
goto end;
if (CONF_modules_load(conf, NULL, 0) <= 0)
goto end;
BIO_free(mem_bio);
return conf;
end:
NCONF_free(conf);
BIO_free(mem_bio);
return NULL;
}
static void free_config_and_unload(CONF *conf)
{
if (conf != NULL) {
NCONF_free(conf);
CONF_modules_unload(1);
}
}
static int verify_module_load(const char *parent_config_file)
{
return OSSL_LIB_CTX_load_config(NULL, parent_config_file);
}
/*
* Returns 1 if the config file entries match the passed in module_mac and
* install_mac values, otherwise it returns 0.
*/
static int verify_config(const char *infile, const char *section,
unsigned char *module_mac, size_t module_mac_len,
unsigned char *install_mac, size_t install_mac_len)
{
int ret = 0;
char *s = NULL;
unsigned char *buf1 = NULL, *buf2 = NULL;
long len;
CONF *conf = NULL;
/* read in the existing values and check they match the saved values */
conf = app_load_config(infile);
if (conf == NULL)
goto end;
s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_VERSION);
if (s == NULL || strcmp(s, VERSION_VAL) != 0) {
BIO_printf(bio_err, "version not found\n");
goto end;
}
s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_MODULE_MAC);
if (s == NULL) {
BIO_printf(bio_err, "Module integrity MAC not found\n");
goto end;
}
buf1 = OPENSSL_hexstr2buf(s, &len);
if (buf1 == NULL
|| (size_t)len != module_mac_len
|| memcmp(module_mac, buf1, module_mac_len) != 0) {
BIO_printf(bio_err, "Module integrity mismatch\n");
goto end;
}
if (install_mac != NULL && install_mac_len > 0) {
s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_STATUS);
if (s == NULL || strcmp(s, INSTALL_STATUS_VAL) != 0) {
BIO_printf(bio_err, "install status not found\n");
goto end;
}
s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_MAC);
if (s == NULL) {
BIO_printf(bio_err, "Install indicator MAC not found\n");
goto end;
}
buf2 = OPENSSL_hexstr2buf(s, &len);
if (buf2 == NULL
|| (size_t)len != install_mac_len
|| memcmp(install_mac, buf2, install_mac_len) != 0) {
BIO_printf(bio_err, "Install indicator status mismatch\n");
goto end;
}
}
ret = 1;
end:
OPENSSL_free(buf1);
OPENSSL_free(buf2);
NCONF_free(conf);
return ret;
}
int fipsinstall_main(int argc, char **argv)
{
int ret = 1, verify = 0, gotkey = 0, gotdigest = 0, pedantic = 0;
const char *section_name = "fips_sect";
const char *mac_name = "HMAC";
const char *prov_name = "fips";
BIO *module_bio = NULL, *mem_bio = NULL, *fout = NULL;
char *in_fname = NULL, *out_fname = NULL, *prog;
char *module_fname = NULL, *parent_config = NULL, *module_path = NULL;
const char *tail;
EVP_MAC_CTX *ctx = NULL, *ctx2 = NULL;
STACK_OF(OPENSSL_STRING) *opts = NULL;
OPTION_CHOICE o;
unsigned char *read_buffer = NULL;
unsigned char module_mac[EVP_MAX_MD_SIZE];
size_t module_mac_len = EVP_MAX_MD_SIZE;
unsigned char install_mac[EVP_MAX_MD_SIZE];
size_t install_mac_len = EVP_MAX_MD_SIZE;
EVP_MAC *mac = NULL;
CONF *conf = NULL;
if ((opts = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
prog = opt_init(argc, argv, fipsinstall_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto cleanup;
case OPT_HELP:
opt_help(fipsinstall_options);
ret = 0;
goto end;
case OPT_IN:
in_fname = opt_arg();
break;
case OPT_OUT:
out_fname = opt_arg();
break;
case OPT_PEDANTIC:
fips_opts = pedantic_opts;
pedantic = 1;
break;
case OPT_NO_CONDITIONAL_ERRORS:
if (!check_non_pedantic_fips(pedantic, "no_conditional_errors"))
goto end;
fips_opts.conditional_errors = 0;
break;
case OPT_NO_SECURITY_CHECKS:
if (!check_non_pedantic_fips(pedantic, "no_security_checks"))
goto end;
fips_opts.security_checks = 0;
break;
case OPT_TLS_PRF_EMS_CHECK:
fips_opts.tls_prf_ems_check = 1;
break;
case OPT_DISALLOW_DRGB_TRUNC_DIGEST:
fips_opts.drgb_no_trunc_dgst = 1;
break;
case OPT_QUIET:
quiet = 1;
/* FALLTHROUGH */
case OPT_NO_LOG:
self_test_log = 0;
break;
case OPT_CORRUPT_DESC:
self_test_corrupt_desc = opt_arg();
break;
case OPT_CORRUPT_TYPE:
self_test_corrupt_type = opt_arg();
break;
case OPT_PROV_NAME:
prov_name = opt_arg();
break;
case OPT_MODULE:
module_fname = opt_arg();
break;
case OPT_SECTION_NAME:
section_name = opt_arg();
break;
case OPT_MAC_NAME:
mac_name = opt_arg();
break;
case OPT_CONFIG:
parent_config = opt_arg();
break;
case OPT_MACOPT:
if (!sk_OPENSSL_STRING_push(opts, opt_arg()))
goto opthelp;
if (HAS_PREFIX(opt_arg(), "hexkey:"))
gotkey = 1;
else if (HAS_PREFIX(opt_arg(), "digest:"))
gotdigest = 1;
break;
case OPT_VERIFY:
verify = 1;
break;
case OPT_SELF_TEST_ONLOAD:
fips_opts.self_test_onload = 1;
break;
case OPT_SELF_TEST_ONINSTALL:
if (!check_non_pedantic_fips(pedantic, "self_test_oninstall"))
goto end;
fips_opts.self_test_onload = 0;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (verify && in_fname == NULL) {
BIO_printf(bio_err, "Missing -in option for -verify\n");
goto opthelp;
}
if (parent_config != NULL) {
/* Test that a parent config can load the module */
if (verify_module_load(parent_config)) {
ret = OSSL_PROVIDER_available(NULL, prov_name) ? 0 : 1;
if (!quiet) {
BIO_printf(bio_err, "FIPS provider is %s\n",
ret == 0 ? "available" : " not available");
}
}
goto end;
}
if (module_fname == NULL)
goto opthelp;
tail = opt_path_end(module_fname);
if (tail != NULL) {
module_path = OPENSSL_strdup(module_fname);
if (module_path == NULL)
goto end;
module_path[tail - module_fname] = '\0';
if (!OSSL_PROVIDER_set_default_search_path(NULL, module_path))
goto end;
}
if (self_test_log
|| self_test_corrupt_desc != NULL
|| self_test_corrupt_type != NULL)
OSSL_SELF_TEST_set_callback(NULL, self_test_events, NULL);
/* Use the default FIPS HMAC digest and key if not specified. */
if (!gotdigest && !sk_OPENSSL_STRING_push(opts, "digest:SHA256"))
goto end;
if (!gotkey && !sk_OPENSSL_STRING_push(opts, "hexkey:" FIPS_KEY_STRING))
goto end;
module_bio = bio_open_default(module_fname, 'r', FORMAT_BINARY);
if (module_bio == NULL) {
BIO_printf(bio_err, "Failed to open module file\n");
goto end;
}
read_buffer = app_malloc(BUFSIZE, "I/O buffer");
if (read_buffer == NULL)
goto end;
mac = EVP_MAC_fetch(app_get0_libctx(), mac_name, app_get0_propq());
if (mac == NULL) {
BIO_printf(bio_err, "Unable to get MAC of type %s\n", mac_name);
goto end;
}
ctx = EVP_MAC_CTX_new(mac);
if (ctx == NULL) {
BIO_printf(bio_err, "Unable to create MAC CTX for module check\n");
goto end;
}
if (opts != NULL) {
int ok = 1;
OSSL_PARAM *params =
app_params_new_from_opts(opts, EVP_MAC_settable_ctx_params(mac));
if (params == NULL)
goto end;
if (!EVP_MAC_CTX_set_params(ctx, params)) {
BIO_printf(bio_err, "MAC parameter error\n");
ERR_print_errors(bio_err);
ok = 0;
}
app_params_free(params);
if (!ok)
goto end;
}
ctx2 = EVP_MAC_CTX_dup(ctx);
if (ctx2 == NULL) {
BIO_printf(bio_err, "Unable to create MAC CTX for install indicator\n");
goto end;
}
if (!do_mac(ctx, read_buffer, module_bio, module_mac, &module_mac_len))
goto end;
if (fips_opts.self_test_onload == 0) {
mem_bio = BIO_new_mem_buf((const void *)INSTALL_STATUS_VAL,
strlen(INSTALL_STATUS_VAL));
if (mem_bio == NULL) {
BIO_printf(bio_err, "Unable to create memory BIO\n");
goto end;
}
if (!do_mac(ctx2, read_buffer, mem_bio, install_mac, &install_mac_len))
goto end;
} else {
install_mac_len = 0;
}
if (verify) {
if (!verify_config(in_fname, section_name, module_mac, module_mac_len,
install_mac, install_mac_len))
goto end;
if (!quiet)
BIO_printf(bio_err, "VERIFY PASSED\n");
} else {
conf = generate_config_and_load(prov_name, section_name, module_mac,
module_mac_len, &fips_opts);
if (conf == NULL)
goto end;
if (!load_fips_prov_and_run_self_test(prov_name))
goto end;
fout =
out_fname == NULL ? dup_bio_out(FORMAT_TEXT)
: bio_open_default(out_fname, 'w', FORMAT_TEXT);
if (fout == NULL) {
BIO_printf(bio_err, "Failed to open file\n");
goto end;
}
if (!write_config_fips_section(fout, section_name,
module_mac, module_mac_len, &fips_opts,
install_mac, install_mac_len))
goto end;
if (!quiet)
BIO_printf(bio_err, "INSTALL PASSED\n");
}
ret = 0;
end:
if (ret == 1) {
if (!quiet)
BIO_printf(bio_err, "%s FAILED\n", verify ? "VERIFY" : "INSTALL");
ERR_print_errors(bio_err);
}
cleanup:
OPENSSL_free(module_path);
BIO_free(fout);
BIO_free(mem_bio);
BIO_free(module_bio);
sk_OPENSSL_STRING_free(opts);
EVP_MAC_free(mac);
EVP_MAC_CTX_free(ctx2);
EVP_MAC_CTX_free(ctx);
OPENSSL_free(read_buffer);
free_config_and_unload(conf);
return ret;
}
static int self_test_events(const OSSL_PARAM params[], void *arg)
{
const OSSL_PARAM *p = NULL;
const char *phase = NULL, *type = NULL, *desc = NULL;
int ret = 0;
p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_PHASE);
if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING)
goto err;
phase = (const char *)p->data;
p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_DESC);
if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING)
goto err;
desc = (const char *)p->data;
p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_TYPE);
if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING)
goto err;
type = (const char *)p->data;
if (self_test_log) {
if (strcmp(phase, OSSL_SELF_TEST_PHASE_START) == 0)
BIO_printf(bio_err, "%s : (%s) : ", desc, type);
else if (strcmp(phase, OSSL_SELF_TEST_PHASE_PASS) == 0
|| strcmp(phase, OSSL_SELF_TEST_PHASE_FAIL) == 0)
BIO_printf(bio_err, "%s\n", phase);
}
/*
* The self test code will internally corrupt the KAT test result if an
* error is returned during the corrupt phase.
*/
if (strcmp(phase, OSSL_SELF_TEST_PHASE_CORRUPT) == 0
&& (self_test_corrupt_desc != NULL
|| self_test_corrupt_type != NULL)) {
if (self_test_corrupt_desc != NULL
&& strcmp(self_test_corrupt_desc, desc) != 0)
goto end;
if (self_test_corrupt_type != NULL
&& strcmp(self_test_corrupt_type, type) != 0)
goto end;
BIO_printf(bio_err, "%s ", phase);
goto err;
}
end:
ret = 1;
err:
return ret;
}
| 22,638 | 32.63893 | 82 |
c
|
openssl
|
openssl-master/apps/gendsa.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/dsa.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_OUT, OPT_PASSOUT, OPT_ENGINE, OPT_CIPHER, OPT_VERBOSE, OPT_QUIET,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS gendsa_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] dsaparam-file\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output the key to the specified file"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
{"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"},
{"verbose", OPT_VERBOSE, '-', "Verbose output"},
{"quiet", OPT_QUIET, '-', "Terse output"},
OPT_PARAMETERS(),
{"dsaparam-file", 0, 0, "File containing DSA parameters"},
{NULL}
};
int gendsa_main(int argc, char **argv)
{
ENGINE *e = NULL;
BIO *out = NULL, *in = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
EVP_CIPHER *enc = NULL;
char *dsaparams = NULL, *ciphername = NULL;
char *outfile = NULL, *passoutarg = NULL, *passout = NULL, *prog;
OPTION_CHOICE o;
int ret = 1, private = 0, verbose = 0, nbits;
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, gendsa_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
ret = 0;
opt_help(gendsa_options);
goto end;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_QUIET:
verbose = 0;
break;
}
}
/* One argument, the params file. */
if (!opt_check_rest_arg("params file"))
goto opthelp;
argv = opt_rest();
dsaparams = argv[0];
if (!app_RAND_load())
goto end;
if (!opt_cipher(ciphername, &enc))
goto end;
private = 1;
if (!app_passwd(NULL, passoutarg, NULL, &passout)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
pkey = load_keyparams(dsaparams, FORMAT_UNDEF, 1, "DSA", "DSA parameters");
out = bio_open_owner(outfile, FORMAT_PEM, private);
if (out == NULL)
goto end2;
nbits = EVP_PKEY_get_bits(pkey);
if (nbits > OPENSSL_DSA_MAX_MODULUS_BITS)
BIO_printf(bio_err,
"Warning: It is not recommended to use more than %d bit for DSA keys.\n"
" Your key size is %d! Larger key size may behave not as expected.\n",
OPENSSL_DSA_MAX_MODULUS_BITS, EVP_PKEY_get_bits(pkey));
ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq());
if (ctx == NULL) {
BIO_printf(bio_err, "unable to create PKEY context\n");
goto end;
}
EVP_PKEY_free(pkey);
pkey = NULL;
if (EVP_PKEY_keygen_init(ctx) <= 0) {
BIO_printf(bio_err, "unable to set up for key generation\n");
goto end;
}
pkey = app_keygen(ctx, "DSA", nbits, verbose);
assert(private);
if (!PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, passout)) {
BIO_printf(bio_err, "unable to output generated key\n");
goto end;
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
end2:
BIO_free(in);
BIO_free_all(out);
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(ctx);
EVP_CIPHER_free(enc);
release_engine(e);
OPENSSL_free(passout);
return ret;
}
| 4,890 | 27.602339 | 97 |
c
|
openssl
|
openssl-master/apps/genpkey.c
|
/*
* Copyright 2006-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/evp.h>
static int verbose = 1;
static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e,
OSSL_LIB_CTX *libctx, const char *propq);
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ENGINE, OPT_OUTFORM, OPT_OUT, OPT_PASS, OPT_PARAMFILE,
OPT_ALGORITHM, OPT_PKEYOPT, OPT_GENPARAM, OPT_TEXT, OPT_CIPHER,
OPT_VERBOSE, OPT_QUIET, OPT_CONFIG,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS genpkey_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"paramfile", OPT_PARAMFILE, '<', "Parameters file"},
{"algorithm", OPT_ALGORITHM, 's', "The public key algorithm"},
{"verbose", OPT_VERBOSE, '-', "Output status while generating keys"},
{"quiet", OPT_QUIET, '-', "Do not output status while generating keys"},
{"pkeyopt", OPT_PKEYOPT, 's',
"Set the public key algorithm option as opt:value"},
OPT_CONFIG_OPTION,
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'F', "output format (DER or PEM)"},
{"pass", OPT_PASS, 's', "Output file pass phrase source"},
{"genparam", OPT_GENPARAM, '-', "Generate parameters, not key"},
{"text", OPT_TEXT, '-', "Print the in text"},
{"", OPT_CIPHER, '-', "Cipher to use to encrypt the key"},
OPT_PROV_OPTIONS,
/* This is deliberately last. */
{OPT_HELP_STR, 1, 1,
"Order of options may be important! See the documentation.\n"},
{NULL}
};
static const char *param_datatype_2name(unsigned int type, int *ishex)
{
*ishex = 0;
switch (type) {
case OSSL_PARAM_INTEGER: return "int";
case OSSL_PARAM_UNSIGNED_INTEGER: return "uint";
case OSSL_PARAM_REAL: return "float";
case OSSL_PARAM_OCTET_STRING: *ishex = 1; return "string";
case OSSL_PARAM_UTF8_STRING: return "string";
default:
return NULL;
}
}
static void show_gen_pkeyopt(const char *algname, OSSL_LIB_CTX *libctx, const char *propq)
{
EVP_PKEY_CTX *ctx = NULL;
const OSSL_PARAM *params;
int i, ishex = 0;
if (algname == NULL)
return;
ctx = EVP_PKEY_CTX_new_from_name(libctx, algname, propq);
if (ctx == NULL)
return;
if (EVP_PKEY_keygen_init(ctx) <= 0)
goto cleanup;
params = EVP_PKEY_CTX_settable_params(ctx);
if (params == NULL)
goto cleanup;
BIO_printf(bio_err, "\nThe possible -pkeyopt arguments are:\n");
for (i = 0; params[i].key != NULL; ++i) {
const char *name = param_datatype_2name(params[i].data_type, &ishex);
if (name != NULL)
BIO_printf(bio_err, " %s%s:%s\n", ishex ? "hex" : "", params[i].key, name);
}
cleanup:
EVP_PKEY_CTX_free(ctx);
}
int genpkey_main(int argc, char **argv)
{
CONF *conf = NULL;
BIO *in = NULL, *out = NULL;
ENGINE *e = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
char *outfile = NULL, *passarg = NULL, *pass = NULL, *prog, *p;
const char *ciphername = NULL, *paramfile = NULL, *algname = NULL;
EVP_CIPHER *cipher = NULL;
OPTION_CHOICE o;
int outformat = FORMAT_PEM, text = 0, ret = 1, rv, do_param = 0;
int private = 0, i;
OSSL_LIB_CTX *libctx = app_get0_libctx();
STACK_OF(OPENSSL_STRING) *keyopt = NULL;
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, genpkey_options);
keyopt = sk_OPENSSL_STRING_new_null();
if (keyopt == NULL)
goto end;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
ret = 0;
opt_help(genpkey_options);
show_gen_pkeyopt(algname, libctx, app_get0_propq());
goto end;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PASS:
passarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PARAMFILE:
if (do_param == 1)
goto opthelp;
paramfile = opt_arg();
break;
case OPT_ALGORITHM:
algname = opt_arg();
break;
case OPT_PKEYOPT:
if (!sk_OPENSSL_STRING_push(keyopt, opt_arg()))
goto end;
break;
case OPT_QUIET:
verbose = 0;
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_GENPARAM:
do_param = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_CONFIG:
conf = app_load_config_modules(opt_arg());
if (conf == NULL)
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
/* Fetch cipher, etc. */
if (paramfile != NULL) {
if (!init_keygen_file(&ctx, paramfile, e, libctx, app_get0_propq()))
goto end;
}
if (algname != NULL) {
if (!init_gen_str(&ctx, algname, e, do_param, libctx, app_get0_propq()))
goto end;
}
if (ctx == NULL)
goto opthelp;
for (i = 0; i < sk_OPENSSL_STRING_num(keyopt); i++) {
p = sk_OPENSSL_STRING_value(keyopt, i);
if (pkey_ctrl_string(ctx, p) <= 0) {
BIO_printf(bio_err, "%s: Error setting %s parameter:\n", prog, p);
ERR_print_errors(bio_err);
goto end;
}
}
if (!opt_cipher(ciphername, &cipher))
goto opthelp;
if (ciphername != NULL && do_param == 1) {
BIO_printf(bio_err, "Cannot use cipher with -genparam option\n");
goto opthelp;
}
private = do_param ? 0 : 1;
if (!app_passwd(passarg, NULL, &pass, NULL)) {
BIO_puts(bio_err, "Error getting password\n");
goto end;
}
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (verbose)
EVP_PKEY_CTX_set_cb(ctx, progress_cb);
EVP_PKEY_CTX_set_app_data(ctx, bio_err);
pkey = do_param ? app_paramgen(ctx, algname)
: app_keygen(ctx, algname, 0, 0 /* not verbose */);
if (do_param) {
rv = PEM_write_bio_Parameters(out, pkey);
} else if (outformat == FORMAT_PEM) {
assert(private);
rv = PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, pass);
} else if (outformat == FORMAT_ASN1) {
assert(private);
rv = i2d_PrivateKey_bio(out, pkey);
} else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
ret = 0;
if (rv <= 0) {
BIO_puts(bio_err, "Error writing key\n");
ret = 1;
}
if (text) {
if (do_param)
rv = EVP_PKEY_print_params(out, pkey, 0, NULL);
else
rv = EVP_PKEY_print_private(out, pkey, 0, NULL);
if (rv <= 0) {
BIO_puts(bio_err, "Error printing key\n");
ret = 1;
}
}
end:
sk_OPENSSL_STRING_free(keyopt);
if (ret != 0)
ERR_print_errors(bio_err);
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(ctx);
EVP_CIPHER_free(cipher);
BIO_free_all(out);
BIO_free(in);
release_engine(e);
OPENSSL_free(pass);
NCONF_free(conf);
return ret;
}
static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e,
OSSL_LIB_CTX *libctx, const char *propq)
{
BIO *pbio;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
if (*pctx) {
BIO_puts(bio_err, "Parameters already set!\n");
return 0;
}
pbio = BIO_new_file(file, "r");
if (pbio == NULL) {
BIO_printf(bio_err, "Can't open parameter file %s\n", file);
return 0;
}
pkey = PEM_read_bio_Parameters_ex(pbio, NULL, libctx, propq);
BIO_free(pbio);
if (pkey == NULL) {
BIO_printf(bio_err, "Error reading parameter file %s\n", file);
return 0;
}
if (e != NULL)
ctx = EVP_PKEY_CTX_new(pkey, e);
else
ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
if (ctx == NULL)
goto err;
if (EVP_PKEY_keygen_init(ctx) <= 0)
goto err;
EVP_PKEY_free(pkey);
*pctx = ctx;
return 1;
err:
BIO_puts(bio_err, "Error initializing context\n");
ERR_print_errors(bio_err);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
return 0;
}
int init_gen_str(EVP_PKEY_CTX **pctx,
const char *algname, ENGINE *e, int do_param,
OSSL_LIB_CTX *libctx, const char *propq)
{
EVP_PKEY_CTX *ctx = NULL;
int pkey_id;
if (*pctx) {
BIO_puts(bio_err, "Algorithm already set!\n");
return 0;
}
pkey_id = get_legacy_pkey_id(libctx, algname, e);
if (pkey_id != NID_undef)
ctx = EVP_PKEY_CTX_new_id(pkey_id, e);
else
ctx = EVP_PKEY_CTX_new_from_name(libctx, algname, propq);
if (ctx == NULL)
goto err;
if (do_param) {
if (EVP_PKEY_paramgen_init(ctx) <= 0)
goto err;
} else {
if (EVP_PKEY_keygen_init(ctx) <= 0)
goto err;
}
*pctx = ctx;
return 1;
err:
BIO_printf(bio_err, "Error initializing %s context\n", algname);
ERR_print_errors(bio_err);
EVP_PKEY_CTX_free(ctx);
return 0;
}
| 10,407 | 27.12973 | 90 |
c
|
openssl
|
openssl-master/apps/genrsa.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#define DEFBITS 2048
#define DEFPRIMES 2
static int verbose = 0;
typedef enum OPTION_choice {
OPT_COMMON,
#ifndef OPENSSL_NO_DEPRECATED_3_0
OPT_3,
#endif
OPT_F4, OPT_ENGINE,
OPT_OUT, OPT_PASSOUT, OPT_CIPHER, OPT_PRIMES, OPT_VERBOSE, OPT_QUIET,
OPT_R_ENUM, OPT_PROV_ENUM, OPT_TRADITIONAL
} OPTION_CHOICE;
const OPTIONS genrsa_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] numbits\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
#ifndef OPENSSL_NO_DEPRECATED_3_0
{"3", OPT_3, '-', "(deprecated) Use 3 for the E value"},
#endif
{"F4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"},
{"f4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output the key to specified file"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
{"primes", OPT_PRIMES, 'p', "Specify number of primes"},
{"verbose", OPT_VERBOSE, '-', "Verbose output"},
{"quiet", OPT_QUIET, '-', "Terse output"},
{"traditional", OPT_TRADITIONAL, '-',
"Use traditional format for private keys"},
{"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"numbits", 0, 0, "Size of key in bits"},
{NULL}
};
int genrsa_main(int argc, char **argv)
{
BN_GENCB *cb = BN_GENCB_new();
ENGINE *eng = NULL;
BIGNUM *bn = BN_new();
BIO *out = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
EVP_CIPHER *enc = NULL;
int ret = 1, num = DEFBITS, private = 0, primes = DEFPRIMES;
unsigned long f4 = RSA_F4;
char *outfile = NULL, *passoutarg = NULL, *passout = NULL;
char *prog, *hexe, *dece, *ciphername = NULL;
OPTION_CHOICE o;
int traditional = 0;
if (bn == NULL || cb == NULL)
goto end;
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, genrsa_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
ret = 0;
opt_help(genrsa_options);
goto end;
#ifndef OPENSSL_NO_DEPRECATED_3_0
case OPT_3:
f4 = RSA_3;
break;
#endif
case OPT_F4:
f4 = RSA_F4;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
eng = setup_engine(opt_arg(), 0);
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_PRIMES:
primes = opt_int_arg();
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_QUIET:
verbose = 0;
break;
case OPT_TRADITIONAL:
traditional = 1;
break;
}
}
/* One optional argument, the bitsize. */
argc = opt_num_rest();
argv = opt_rest();
if (argc == 1) {
if (!opt_int(argv[0], &num) || num <= 0)
goto end;
if (num > OPENSSL_RSA_MAX_MODULUS_BITS)
BIO_printf(bio_err,
"Warning: It is not recommended to use more than %d bit for RSA keys.\n"
" Your key size is %d! Larger key size may behave not as expected.\n",
OPENSSL_RSA_MAX_MODULUS_BITS, num);
} else if (!opt_check_rest_arg(NULL)) {
goto opthelp;
}
if (!app_RAND_load())
goto end;
private = 1;
if (!opt_cipher(ciphername, &enc))
goto end;
if (!app_passwd(NULL, passoutarg, NULL, &passout)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
out = bio_open_owner(outfile, FORMAT_PEM, private);
if (out == NULL)
goto end;
if (!init_gen_str(&ctx, "RSA", eng, 0, app_get0_libctx(),
app_get0_propq()))
goto end;
if (verbose)
EVP_PKEY_CTX_set_cb(ctx, progress_cb);
EVP_PKEY_CTX_set_app_data(ctx, bio_err);
if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, num) <= 0) {
BIO_printf(bio_err, "Error setting RSA length\n");
goto end;
}
if (!BN_set_word(bn, f4)) {
BIO_printf(bio_err, "Error allocating RSA public exponent\n");
goto end;
}
if (EVP_PKEY_CTX_set1_rsa_keygen_pubexp(ctx, bn) <= 0) {
BIO_printf(bio_err, "Error setting RSA public exponent\n");
goto end;
}
if (EVP_PKEY_CTX_set_rsa_keygen_primes(ctx, primes) <= 0) {
BIO_printf(bio_err, "Error setting number of primes\n");
goto end;
}
pkey = app_keygen(ctx, "RSA", num, verbose);
if (verbose) {
BIGNUM *e = NULL;
/* Every RSA key has an 'e' */
EVP_PKEY_get_bn_param(pkey, "e", &e);
if (e == NULL) {
BIO_printf(bio_err, "Error cannot access RSA e\n");
goto end;
}
hexe = BN_bn2hex(e);
dece = BN_bn2dec(e);
if (hexe && dece) {
BIO_printf(bio_err, "e is %s (0x%s)\n", dece, hexe);
}
OPENSSL_free(hexe);
OPENSSL_free(dece);
BN_free(e);
}
if (traditional) {
if (!PEM_write_bio_PrivateKey_traditional(out, pkey, enc, NULL, 0,
NULL, passout))
goto end;
} else {
if (!PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, passout))
goto end;
}
ret = 0;
end:
BN_free(bn);
BN_GENCB_free(cb);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
EVP_CIPHER_free(enc);
BIO_free_all(out);
release_engine(eng);
OPENSSL_free(passout);
if (ret != 0)
ERR_print_errors(bio_err);
return ret;
}
| 7,064 | 27.26 | 101 |
c
|
openssl
|
openssl-master/apps/info.c
|
/*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/crypto.h>
#include "apps.h"
#include "progs.h"
typedef enum OPTION_choice {
OPT_COMMON,
OPT_CONFIGDIR, OPT_ENGINESDIR, OPT_MODULESDIR, OPT_DSOEXT, OPT_DIRNAMESEP,
OPT_LISTSEP, OPT_SEEDS, OPT_CPUSETTINGS
} OPTION_CHOICE;
const OPTIONS info_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("Output"),
{"configdir", OPT_CONFIGDIR, '-', "Default configuration file directory"},
{"enginesdir", OPT_ENGINESDIR, '-', "Default engine module directory"},
{"modulesdir", OPT_MODULESDIR, '-',
"Default module directory (other than engine modules)"},
{"dsoext", OPT_DSOEXT, '-', "Configured extension for modules"},
{"dirnamesep", OPT_DIRNAMESEP, '-', "Directory-filename separator"},
{"listsep", OPT_LISTSEP, '-', "List separator character"},
{"seeds", OPT_SEEDS, '-', "Seed sources"},
{"cpusettings", OPT_CPUSETTINGS, '-', "CPU settings info"},
{NULL}
};
int info_main(int argc, char **argv)
{
int ret = 1, dirty = 0, type = 0;
char *prog;
OPTION_CHOICE o;
prog = opt_init(argc, argv, info_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
default:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(info_options);
ret = 0;
goto end;
case OPT_CONFIGDIR:
type = OPENSSL_INFO_CONFIG_DIR;
dirty++;
break;
case OPT_ENGINESDIR:
type = OPENSSL_INFO_ENGINES_DIR;
dirty++;
break;
case OPT_MODULESDIR:
type = OPENSSL_INFO_MODULES_DIR;
dirty++;
break;
case OPT_DSOEXT:
type = OPENSSL_INFO_DSO_EXTENSION;
dirty++;
break;
case OPT_DIRNAMESEP:
type = OPENSSL_INFO_DIR_FILENAME_SEPARATOR;
dirty++;
break;
case OPT_LISTSEP:
type = OPENSSL_INFO_LIST_SEPARATOR;
dirty++;
break;
case OPT_SEEDS:
type = OPENSSL_INFO_SEED_SOURCE;
dirty++;
break;
case OPT_CPUSETTINGS:
type = OPENSSL_INFO_CPU_SETTINGS;
dirty++;
break;
}
}
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (dirty > 1) {
BIO_printf(bio_err, "%s: Only one item allowed\n", prog);
goto opthelp;
}
if (dirty == 0) {
BIO_printf(bio_err, "%s: No items chosen\n", prog);
goto opthelp;
}
BIO_printf(bio_out, "%s\n", OPENSSL_info(type));
ret = 0;
end:
return ret;
}
| 3,071 | 28.257143 | 78 |
c
|
openssl
|
openssl-master/apps/kdf.c
|
/*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_KDFOPT, OPT_BIN, OPT_KEYLEN, OPT_OUT,
OPT_CIPHER, OPT_DIGEST, OPT_MAC,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS kdf_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] kdf_name\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"kdfopt", OPT_KDFOPT, 's', "KDF algorithm control parameters in n:v form"},
{"cipher", OPT_CIPHER, 's', "Cipher"},
{"digest", OPT_DIGEST, 's', "Digest"},
{"mac", OPT_MAC, 's', "MAC"},
{OPT_MORE_STR, 1, '-', "See 'Supported Controls' in the EVP_KDF_ docs\n"},
{"keylen", OPT_KEYLEN, 's', "The size of the output derived key"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output to filename rather than stdout"},
{"binary", OPT_BIN, '-',
"Output in binary format (default is hexadecimal)"},
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"kdf_name", 0, 0, "Name of the KDF algorithm"},
{NULL}
};
static char *alloc_kdf_algorithm_name(STACK_OF(OPENSSL_STRING) **optp,
const char *name, const char *arg)
{
size_t len = strlen(name) + strlen(arg) + 2;
char *res;
if (*optp == NULL)
*optp = sk_OPENSSL_STRING_new_null();
if (*optp == NULL)
return NULL;
res = app_malloc(len, "algorithm name");
BIO_snprintf(res, len, "%s:%s", name, arg);
if (sk_OPENSSL_STRING_push(*optp, res))
return res;
OPENSSL_free(res);
return NULL;
}
int kdf_main(int argc, char **argv)
{
int ret = 1, out_bin = 0;
OPTION_CHOICE o;
STACK_OF(OPENSSL_STRING) *opts = NULL;
char *prog, *hexout = NULL;
const char *outfile = NULL;
unsigned char *dkm_bytes = NULL;
size_t dkm_len = 0;
BIO *out = NULL;
EVP_KDF *kdf = NULL;
EVP_KDF_CTX *ctx = NULL;
char *digest = NULL, *cipher = NULL, *mac = NULL;
prog = opt_init(argc, argv, kdf_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
default:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto err;
case OPT_HELP:
opt_help(kdf_options);
ret = 0;
goto err;
case OPT_BIN:
out_bin = 1;
break;
case OPT_KEYLEN:
dkm_len = (size_t)atoi(opt_arg());
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_KDFOPT:
if (opts == NULL)
opts = sk_OPENSSL_STRING_new_null();
if (opts == NULL || !sk_OPENSSL_STRING_push(opts, opt_arg()))
goto opthelp;
break;
case OPT_CIPHER:
OPENSSL_free(cipher);
cipher = alloc_kdf_algorithm_name(&opts, "cipher", opt_arg());
if (cipher == NULL)
goto opthelp;
break;
case OPT_DIGEST:
OPENSSL_free(digest);
digest = alloc_kdf_algorithm_name(&opts, "digest", opt_arg());
if (digest == NULL)
goto opthelp;
break;
case OPT_MAC:
OPENSSL_free(mac);
mac = alloc_kdf_algorithm_name(&opts, "mac", opt_arg());
if (mac == NULL)
goto opthelp;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto err;
break;
}
}
/* One argument, the KDF name. */
argc = opt_num_rest();
argv = opt_rest();
if (argc != 1)
goto opthelp;
if ((kdf = EVP_KDF_fetch(app_get0_libctx(), argv[0],
app_get0_propq())) == NULL) {
BIO_printf(bio_err, "Invalid KDF name %s\n", argv[0]);
goto opthelp;
}
ctx = EVP_KDF_CTX_new(kdf);
if (ctx == NULL)
goto err;
if (opts != NULL) {
int ok = 1;
OSSL_PARAM *params =
app_params_new_from_opts(opts, EVP_KDF_settable_ctx_params(kdf));
if (params == NULL)
goto err;
if (!EVP_KDF_CTX_set_params(ctx, params)) {
BIO_printf(bio_err, "KDF parameter error\n");
ERR_print_errors(bio_err);
ok = 0;
}
app_params_free(params);
if (!ok)
goto err;
}
out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT);
if (out == NULL)
goto err;
if (dkm_len <= 0) {
BIO_printf(bio_err, "Invalid derived key length.\n");
goto err;
}
dkm_bytes = app_malloc(dkm_len, "out buffer");
if (dkm_bytes == NULL)
goto err;
if (!EVP_KDF_derive(ctx, dkm_bytes, dkm_len, NULL)) {
BIO_printf(bio_err, "EVP_KDF_derive failed\n");
goto err;
}
if (out_bin) {
BIO_write(out, dkm_bytes, dkm_len);
} else {
hexout = OPENSSL_buf2hexstr(dkm_bytes, dkm_len);
if (hexout == NULL) {
BIO_printf(bio_err, "Memory allocation failure\n");
goto err;
}
BIO_printf(out, "%s\n\n", hexout);
}
ret = 0;
err:
if (ret != 0)
ERR_print_errors(bio_err);
OPENSSL_clear_free(dkm_bytes, dkm_len);
sk_OPENSSL_STRING_free(opts);
EVP_KDF_free(kdf);
EVP_KDF_CTX_free(ctx);
BIO_free(out);
OPENSSL_free(hexout);
OPENSSL_free(cipher);
OPENSSL_free(digest);
OPENSSL_free(mac);
return ret;
}
| 5,957 | 27.103774 | 80 |
c
|
openssl
|
openssl-master/apps/mac.c
|
/*
* Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/params.h>
#include <openssl/core_names.h>
#undef BUFSIZE
#define BUFSIZE 1024*8
typedef enum OPTION_choice {
OPT_COMMON,
OPT_MACOPT, OPT_BIN, OPT_IN, OPT_OUT,
OPT_CIPHER, OPT_DIGEST,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS mac_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] mac_name\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form"},
{"cipher", OPT_CIPHER, 's', "Cipher"},
{"digest", OPT_DIGEST, 's', "Digest"},
{OPT_MORE_STR, 1, '-', "See 'PARAMETER NAMES' in the EVP_MAC_ docs"},
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file to MAC (default is stdin)"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output to filename rather than stdout"},
{"binary", OPT_BIN, '-',
"Output in binary format (default is hexadecimal)"},
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"mac_name", 0, 0, "MAC algorithm"},
{NULL}
};
static char *alloc_mac_algorithm_name(STACK_OF(OPENSSL_STRING) **optp,
const char *name, const char *arg)
{
size_t len = strlen(name) + strlen(arg) + 2;
char *res;
if (*optp == NULL)
*optp = sk_OPENSSL_STRING_new_null();
if (*optp == NULL)
return NULL;
res = app_malloc(len, "algorithm name");
BIO_snprintf(res, len, "%s:%s", name, arg);
if (sk_OPENSSL_STRING_push(*optp, res))
return res;
OPENSSL_free(res);
return NULL;
}
int mac_main(int argc, char **argv)
{
int ret = 1;
char *prog;
EVP_MAC *mac = NULL;
OPTION_CHOICE o;
EVP_MAC_CTX *ctx = NULL;
STACK_OF(OPENSSL_STRING) *opts = NULL;
unsigned char *buf = NULL;
size_t len;
int i;
BIO *in = NULL, *out = NULL;
const char *outfile = NULL;
const char *infile = NULL;
int out_bin = 0;
int inform = FORMAT_BINARY;
char *digest = NULL, *cipher = NULL;
OSSL_PARAM *params = NULL;
prog = opt_init(argc, argv, mac_options);
buf = app_malloc(BUFSIZE, "I/O buffer");
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
default:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto err;
case OPT_HELP:
opt_help(mac_options);
ret = 0;
goto err;
case OPT_BIN:
out_bin = 1;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_MACOPT:
if (opts == NULL)
opts = sk_OPENSSL_STRING_new_null();
if (opts == NULL || !sk_OPENSSL_STRING_push(opts, opt_arg()))
goto opthelp;
break;
case OPT_CIPHER:
OPENSSL_free(cipher);
cipher = alloc_mac_algorithm_name(&opts, "cipher", opt_arg());
if (cipher == NULL)
goto opthelp;
break;
case OPT_DIGEST:
OPENSSL_free(digest);
digest = alloc_mac_algorithm_name(&opts, "digest", opt_arg());
if (digest == NULL)
goto opthelp;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto err;
break;
}
}
/* One argument, the MAC name. */
if (!opt_check_rest_arg("MAC name"))
goto opthelp;
argv = opt_rest();
mac = EVP_MAC_fetch(app_get0_libctx(), argv[0], app_get0_propq());
if (mac == NULL) {
BIO_printf(bio_err, "Invalid MAC name %s\n", argv[0]);
goto opthelp;
}
ctx = EVP_MAC_CTX_new(mac);
if (ctx == NULL)
goto err;
if (opts != NULL) {
int ok = 1;
params = app_params_new_from_opts(opts,
EVP_MAC_settable_ctx_params(mac));
if (params == NULL)
goto err;
if (!EVP_MAC_CTX_set_params(ctx, params)) {
BIO_printf(bio_err, "MAC parameter error\n");
ERR_print_errors(bio_err);
ok = 0;
}
app_params_free(params);
if (!ok)
goto err;
}
in = bio_open_default(infile, 'r', inform);
if (in == NULL)
goto err;
out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT);
if (out == NULL)
goto err;
if (!EVP_MAC_init(ctx, NULL, 0, NULL)) {
BIO_printf(bio_err, "EVP_MAC_Init failed\n");
goto err;
}
while (BIO_pending(in) || !BIO_eof(in)) {
i = BIO_read(in, (char *)buf, BUFSIZE);
if (i < 0) {
BIO_printf(bio_err, "Read Error in '%s'\n", infile);
ERR_print_errors(bio_err);
goto err;
}
if (i == 0)
break;
if (!EVP_MAC_update(ctx, buf, i)) {
BIO_printf(bio_err, "EVP_MAC_update failed\n");
goto err;
}
}
if (!EVP_MAC_final(ctx, NULL, &len, 0)) {
BIO_printf(bio_err, "EVP_MAC_final failed\n");
goto err;
}
if (len > BUFSIZE) {
BIO_printf(bio_err, "output len is too large\n");
goto err;
}
if (!EVP_MAC_final(ctx, buf, &len, BUFSIZE)) {
BIO_printf(bio_err, "EVP_MAC_final failed\n");
goto err;
}
if (out_bin) {
BIO_write(out, buf, len);
} else {
for (i = 0; i < (int)len; ++i)
BIO_printf(out, "%02X", buf[i]);
if (outfile == NULL)
BIO_printf(out, "\n");
}
ret = 0;
err:
if (ret != 0)
ERR_print_errors(bio_err);
OPENSSL_clear_free(buf, BUFSIZE);
OPENSSL_free(cipher);
OPENSSL_free(digest);
sk_OPENSSL_STRING_free(opts);
BIO_free(in);
BIO_free(out);
EVP_MAC_CTX_free(ctx);
EVP_MAC_free(mac);
return ret;
}
| 6,388 | 25.957806 | 80 |
c
|
openssl
|
openssl-master/apps/nseq.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/pem.h>
#include <openssl/err.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_TOSEQ, OPT_IN, OPT_OUT,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS nseq_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
OPT_SECTION("Output"),
{"toseq", OPT_TOSEQ, '-', "Output NS Sequence file"},
{"out", OPT_OUT, '>', "Output file"},
OPT_PROV_OPTIONS,
{NULL}
};
int nseq_main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL;
X509 *x509 = NULL;
NETSCAPE_CERT_SEQUENCE *seq = NULL;
OPTION_CHOICE o;
int toseq = 0, ret = 1, i;
char *infile = NULL, *outfile = NULL, *prog;
prog = opt_init(argc, argv, nseq_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
ret = 0;
opt_help(nseq_options);
goto end;
case OPT_TOSEQ:
toseq = 1;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
in = bio_open_default(infile, 'r', FORMAT_PEM);
if (in == NULL)
goto end;
out = bio_open_default(outfile, 'w', FORMAT_PEM);
if (out == NULL)
goto end;
if (toseq) {
seq = NETSCAPE_CERT_SEQUENCE_new();
if (seq == NULL)
goto end;
seq->certs = sk_X509_new_null();
if (seq->certs == NULL)
goto end;
while ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
if (!sk_X509_push(seq->certs, x509))
goto end;
}
if (!sk_X509_num(seq->certs)) {
BIO_printf(bio_err, "%s: Error reading certs file %s\n",
prog, infile);
ERR_print_errors(bio_err);
goto end;
}
PEM_write_bio_NETSCAPE_CERT_SEQUENCE(out, seq);
ret = 0;
goto end;
}
seq = PEM_read_bio_NETSCAPE_CERT_SEQUENCE(in, NULL, NULL, NULL);
if (seq == NULL) {
BIO_printf(bio_err, "%s: Error reading sequence file %s\n",
prog, infile);
ERR_print_errors(bio_err);
goto end;
}
for (i = 0; i < sk_X509_num(seq->certs); i++) {
x509 = sk_X509_value(seq->certs, i);
dump_cert_text(out, x509);
PEM_write_bio_X509(out, x509);
}
ret = 0;
end:
BIO_free(in);
BIO_free_all(out);
NETSCAPE_CERT_SEQUENCE_free(seq);
return ret;
}
| 3,348 | 24.761538 | 74 |
c
|
openssl
|
openssl-master/apps/openssl.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include "internal/common.h"
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/trace.h>
#include <openssl/lhash.h>
#include <openssl/conf.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#include <openssl/err.h>
/* Needed to get the other O_xxx flags. */
#ifdef OPENSSL_SYS_VMS
# include <unixio.h>
#endif
#include "apps.h"
#include "progs.h"
/*
* The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
* the base prototypes (we cast each variable inside the function to the
* required type of "FUNCTION*"). This removes the necessity for
* macro-generated wrapper functions.
*/
static LHASH_OF(FUNCTION) *prog_init(void);
static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
char *default_config_file = NULL;
BIO *bio_in = NULL;
BIO *bio_out = NULL;
BIO *bio_err = NULL;
static void warn_deprecated(const FUNCTION *fp)
{
if (fp->deprecated_version != NULL)
BIO_printf(bio_err, "The command %s was deprecated in version %s.",
fp->name, fp->deprecated_version);
else
BIO_printf(bio_err, "The command %s is deprecated.", fp->name);
if (strcmp(fp->deprecated_alternative, DEPRECATED_NO_ALTERNATIVE) != 0)
BIO_printf(bio_err, " Use '%s' instead.", fp->deprecated_alternative);
BIO_printf(bio_err, "\n");
}
static int apps_startup(void)
{
const char *use_libctx = NULL;
#ifdef SIGPIPE
signal(SIGPIPE, SIG_IGN);
#endif
/* Set non-default library initialisation settings */
if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN
| OPENSSL_INIT_LOAD_CONFIG, NULL))
return 0;
(void)setup_ui_method();
(void)setup_engine_loader();
/*
* NOTE: This is an undocumented feature required for testing only.
* There are no guarantees that it will exist in future builds.
*/
use_libctx = getenv("OPENSSL_TEST_LIBCTX");
if (use_libctx != NULL) {
/* Set this to "1" to create a global libctx */
if (strcmp(use_libctx, "1") == 0) {
if (app_create_libctx() == NULL)
return 0;
}
}
return 1;
}
static void apps_shutdown(void)
{
app_providers_cleanup();
OSSL_LIB_CTX_free(app_get0_libctx());
destroy_engine_loader();
destroy_ui_method();
}
#ifndef OPENSSL_NO_TRACE
typedef struct tracedata_st {
BIO *bio;
unsigned int ingroup:1;
} tracedata;
static size_t internal_trace_cb(const char *buf, size_t cnt,
int category, int cmd, void *vdata)
{
int ret = 0;
tracedata *trace_data = vdata;
char buffer[256], *hex;
CRYPTO_THREAD_ID tid;
switch (cmd) {
case OSSL_TRACE_CTRL_BEGIN:
if (trace_data->ingroup) {
BIO_printf(bio_err, "ERROR: tracing already started\n");
return 0;
}
trace_data->ingroup = 1;
tid = CRYPTO_THREAD_get_current_id();
hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid));
BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ",
hex == NULL ? "<null>" : hex,
OSSL_trace_get_category_name(category));
OPENSSL_free(hex);
BIO_set_prefix(trace_data->bio, buffer);
break;
case OSSL_TRACE_CTRL_WRITE:
if (!trace_data->ingroup) {
BIO_printf(bio_err, "ERROR: writing when tracing not started\n");
return 0;
}
ret = BIO_write(trace_data->bio, buf, cnt);
break;
case OSSL_TRACE_CTRL_END:
if (!trace_data->ingroup) {
BIO_printf(bio_err, "ERROR: finishing when tracing not started\n");
return 0;
}
trace_data->ingroup = 0;
BIO_set_prefix(trace_data->bio, NULL);
break;
}
return ret < 0 ? 0 : ret;
}
DEFINE_STACK_OF(tracedata)
static STACK_OF(tracedata) *trace_data_stack;
static void tracedata_free(tracedata *data)
{
BIO_free_all(data->bio);
OPENSSL_free(data);
}
static STACK_OF(tracedata) *trace_data_stack;
static void cleanup_trace(void)
{
sk_tracedata_pop_free(trace_data_stack, tracedata_free);
}
static void setup_trace_category(int category)
{
BIO *channel;
tracedata *trace_data;
BIO *bio = NULL;
if (OSSL_trace_enabled(category))
return;
bio = BIO_new(BIO_f_prefix());
channel = BIO_push(bio, dup_bio_err(FORMAT_TEXT));
trace_data = OPENSSL_zalloc(sizeof(*trace_data));
if (trace_data == NULL
|| bio == NULL
|| (trace_data->bio = channel) == NULL
|| OSSL_trace_set_callback(category, internal_trace_cb,
trace_data) == 0
|| sk_tracedata_push(trace_data_stack, trace_data) == 0) {
fprintf(stderr,
"warning: unable to setup trace callback for category '%s'.\n",
OSSL_trace_get_category_name(category));
OSSL_trace_set_callback(category, NULL, NULL);
BIO_free_all(channel);
}
}
static void setup_trace(const char *str)
{
char *val;
/*
* We add this handler as early as possible to ensure it's executed
* as late as possible, i.e. after the TRACE code has done its cleanup
* (which happens last in OPENSSL_cleanup).
*/
atexit(cleanup_trace);
trace_data_stack = sk_tracedata_new_null();
val = OPENSSL_strdup(str);
if (val != NULL) {
char *valp = val;
char *item;
for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) {
int category = OSSL_trace_get_category_num(item);
if (category == OSSL_TRACE_CATEGORY_ALL) {
while (++category < OSSL_TRACE_CATEGORY_NUM)
setup_trace_category(category);
break;
} else if (category > 0) {
setup_trace_category(category);
} else {
fprintf(stderr,
"warning: unknown trace category: '%s'.\n", item);
}
}
}
OPENSSL_free(val);
}
#endif /* OPENSSL_NO_TRACE */
static char *help_argv[] = { "help", NULL };
static char *version_argv[] = { "version", NULL };
int main(int argc, char *argv[])
{
FUNCTION f, *fp;
LHASH_OF(FUNCTION) *prog = NULL;
char *pname;
const char *fname;
ARGS arg;
int global_help = 0;
int global_version = 0;
int ret = 0;
arg.argv = NULL;
arg.size = 0;
/* Set up some of the environment. */
bio_in = dup_bio_in(FORMAT_TEXT);
bio_out = dup_bio_out(FORMAT_TEXT);
bio_err = dup_bio_err(FORMAT_TEXT);
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
argv = copy_argv(&argc, argv);
#elif defined(_WIN32)
/* Replace argv[] with UTF-8 encoded strings. */
win32_utf8argv(&argc, &argv);
#endif
#ifndef OPENSSL_NO_TRACE
setup_trace(getenv("OPENSSL_TRACE"));
#endif
if ((fname = "apps_startup", !apps_startup())
|| (fname = "prog_init", (prog = prog_init()) == NULL)) {
BIO_printf(bio_err,
"FATAL: Startup failure (dev note: %s()) for %s\n",
fname, argv[0]);
ERR_print_errors(bio_err);
ret = 1;
goto end;
}
pname = opt_progname(argv[0]);
default_config_file = CONF_get1_default_config_file();
if (default_config_file == NULL)
app_bail_out("%s: could not get default config file\n", pname);
/* first check the program name */
f.name = pname;
fp = lh_FUNCTION_retrieve(prog, &f);
if (fp == NULL) {
/* We assume we've been called as 'openssl ...' */
global_help = argc > 1
&& (strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0
|| strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--h") == 0);
global_version = argc > 1
&& (strcmp(argv[1], "-version") == 0 || strcmp(argv[1], "--version") == 0
|| strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--v") == 0);
argc--;
argv++;
opt_appname(argc == 1 || global_help ? "help" : global_version ? "version" : argv[0]);
} else {
argv[0] = pname;
}
/*
* If there's no command, assume "help". If there's an override for help
* or version run those, otherwise run the command given.
*/
ret = (argc == 0) || global_help
? do_cmd(prog, 1, help_argv)
: global_version
? do_cmd(prog, 1, version_argv)
: do_cmd(prog, argc, argv);
end:
OPENSSL_free(default_config_file);
lh_FUNCTION_free(prog);
OPENSSL_free(arg.argv);
if (!app_RAND_write())
ret = EXIT_FAILURE;
BIO_free(bio_in);
BIO_free_all(bio_out);
apps_shutdown();
BIO_free_all(bio_err);
EXIT(ret);
}
typedef enum HELP_CHOICE {
OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP
} HELP_CHOICE;
const OPTIONS help_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"},
OPT_SECTION("General"),
{"help", OPT_hHELP, '-', "Display this summary"},
OPT_PARAMETERS(),
{"command", 0, 0, "Name of command to display help (optional)"},
{NULL}
};
int help_main(int argc, char **argv)
{
FUNCTION *fp;
int i, nl;
FUNC_TYPE tp;
char *prog;
HELP_CHOICE o;
DISPLAY_COLUMNS dc;
char *new_argv[3];
prog = opt_init(argc, argv, help_options);
while ((o = opt_next()) != OPT_hEOF) {
switch (o) {
case OPT_hERR:
case OPT_hEOF:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
return 1;
case OPT_hHELP:
opt_help(help_options);
return 0;
}
}
/* One optional argument, the command to get help for. */
if (opt_num_rest() == 1) {
new_argv[0] = opt_rest()[0];
new_argv[1] = "--help";
new_argv[2] = NULL;
return do_cmd(prog_init(), 2, new_argv);
}
if (!opt_check_rest_arg(NULL)) {
BIO_printf(bio_err, "Usage: %s\n", prog);
return 1;
}
calculate_columns(functions, &dc);
BIO_printf(bio_err, "%s:\n\nStandard commands", prog);
i = 0;
tp = FT_none;
for (fp = functions; fp->name != NULL; fp++) {
nl = 0;
if (i++ % dc.columns == 0) {
BIO_printf(bio_err, "\n");
nl = 1;
}
if (fp->type != tp) {
tp = fp->type;
if (!nl)
BIO_printf(bio_err, "\n");
if (tp == FT_md) {
i = 1;
BIO_printf(bio_err,
"\nMessage Digest commands (see the `dgst' command for more details)\n");
} else if (tp == FT_cipher) {
i = 1;
BIO_printf(bio_err,
"\nCipher commands (see the `enc' command for more details)\n");
}
}
BIO_printf(bio_err, "%-*s", dc.width, fp->name);
}
BIO_printf(bio_err, "\n\n");
return 0;
}
static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
{
FUNCTION f, *fp;
if (argc <= 0 || argv[0] == NULL)
return 0;
memset(&f, 0, sizeof(f));
f.name = argv[0];
fp = lh_FUNCTION_retrieve(prog, &f);
if (fp == NULL) {
if (EVP_get_digestbyname(argv[0])) {
f.type = FT_md;
f.func = dgst_main;
fp = &f;
} else if (EVP_get_cipherbyname(argv[0])) {
f.type = FT_cipher;
f.func = enc_main;
fp = &f;
}
}
if (fp != NULL) {
if (fp->deprecated_alternative != NULL)
warn_deprecated(fp);
return fp->func(argc, argv);
}
f.name = argv[0];
if (CHECK_AND_SKIP_PREFIX(f.name, "no-")) {
/*
* User is asking if foo is unsupported, by trying to "run" the
* no-foo command. Strange.
*/
if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
BIO_printf(bio_out, "%s\n", argv[0]);
return 0;
}
BIO_printf(bio_out, "%s\n", argv[0] + 3);
return 1;
}
BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
argv[0]);
return 1;
}
static int function_cmp(const FUNCTION * a, const FUNCTION * b)
{
return strncmp(a->name, b->name, 8);
}
static unsigned long function_hash(const FUNCTION * a)
{
return OPENSSL_LH_strhash(a->name);
}
static int SortFnByName(const void *_f1, const void *_f2)
{
const FUNCTION *f1 = _f1;
const FUNCTION *f2 = _f2;
if (f1->type != f2->type)
return f1->type - f2->type;
return strcmp(f1->name, f2->name);
}
static LHASH_OF(FUNCTION) *prog_init(void)
{
static LHASH_OF(FUNCTION) *ret = NULL;
static int prog_inited = 0;
FUNCTION *f;
size_t i;
if (prog_inited)
return ret;
prog_inited = 1;
/* Sort alphabetically within category. For nicer help displays. */
for (i = 0, f = functions; f->name != NULL; ++f, ++i)
;
qsort(functions, i, sizeof(*functions), SortFnByName);
if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL)
return NULL;
for (f = functions; f->name != NULL; f++)
(void)lh_FUNCTION_insert(ret, f);
return ret;
}
| 13,712 | 26.815416 | 100 |
c
|
openssl
|
openssl-master/apps/pkcs7.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "apps.h"
#include "progs.h"
#include <openssl/err.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pkcs7.h>
#include <openssl/pem.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_NOOUT,
OPT_TEXT, OPT_PRINT, OPT_PRINT_CERTS, OPT_QUIET,
OPT_ENGINE, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS pkcs7_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
OPT_SECTION("Output"),
{"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
{"out", OPT_OUT, '>', "Output file"},
{"noout", OPT_NOOUT, '-', "Don't output encoded data"},
{"text", OPT_TEXT, '-', "Print full details of certificates"},
{"print", OPT_PRINT, '-', "Print out all fields of the PKCS7 structure"},
{"print_certs", OPT_PRINT_CERTS, '-',
"Print_certs print any certs or crl in the input"},
{"quiet", OPT_QUIET, '-',
"When used with -print_certs, it produces a cleaner output"},
OPT_PROV_OPTIONS,
{NULL}
};
int pkcs7_main(int argc, char **argv)
{
ENGINE *e = NULL;
PKCS7 *p7 = NULL, *p7i;
BIO *in = NULL, *out = NULL;
int informat = FORMAT_PEM, outformat = FORMAT_PEM;
char *infile = NULL, *outfile = NULL, *prog;
int i, print_certs = 0, text = 0, noout = 0, p7_print = 0, quiet = 0, ret = 1;
OPTION_CHOICE o;
OSSL_LIB_CTX *libctx = app_get0_libctx();
prog = opt_init(argc, argv, pkcs7_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(pkcs7_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_PRINT:
p7_print = 1;
break;
case OPT_PRINT_CERTS:
print_certs = 1;
break;
case OPT_QUIET:
quiet = 1;
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
in = bio_open_default(infile, 'r', informat);
if (in == NULL)
goto end;
p7 = PKCS7_new_ex(libctx, app_get0_propq());
if (p7 == NULL) {
BIO_printf(bio_err, "unable to allocate PKCS7 object\n");
ERR_print_errors(bio_err);
goto end;
}
if (informat == FORMAT_ASN1)
p7i = d2i_PKCS7_bio(in, &p7);
else
p7i = PEM_read_bio_PKCS7(in, &p7, NULL, NULL);
if (p7i == NULL) {
BIO_printf(bio_err, "unable to load PKCS7 object\n");
ERR_print_errors(bio_err);
goto end;
}
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
if (p7_print)
PKCS7_print_ctx(out, p7, 0, NULL);
if (print_certs) {
STACK_OF(X509) *certs = NULL;
STACK_OF(X509_CRL) *crls = NULL;
i = OBJ_obj2nid(p7->type);
switch (i) {
case NID_pkcs7_signed:
if (p7->d.sign != NULL) {
certs = p7->d.sign->cert;
crls = p7->d.sign->crl;
}
break;
case NID_pkcs7_signedAndEnveloped:
if (p7->d.signed_and_enveloped != NULL) {
certs = p7->d.signed_and_enveloped->cert;
crls = p7->d.signed_and_enveloped->crl;
}
break;
default:
break;
}
if (certs != NULL) {
X509 *x;
for (i = 0; i < sk_X509_num(certs); i++) {
x = sk_X509_value(certs, i);
if (text)
X509_print(out, x);
else if (!quiet)
dump_cert_text(out, x);
if (!noout)
PEM_write_bio_X509(out, x);
BIO_puts(out, "\n");
}
}
if (crls != NULL) {
X509_CRL *crl;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
X509_CRL_print_ex(out, crl, get_nameopt());
if (!noout)
PEM_write_bio_X509_CRL(out, crl);
BIO_puts(out, "\n");
}
}
ret = 0;
goto end;
}
if (!noout) {
if (outformat == FORMAT_ASN1)
i = i2d_PKCS7_bio(out, p7);
else
i = PEM_write_bio_PKCS7(out, p7);
if (!i) {
BIO_printf(bio_err, "unable to write pkcs7 object\n");
ERR_print_errors(bio_err);
goto end;
}
}
ret = 0;
end:
PKCS7_free(p7);
release_engine(e);
BIO_free(in);
BIO_free_all(out);
return ret;
}
| 6,189 | 26.511111 | 82 |
c
|
openssl
|
openssl-master/apps/pkcs8.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pkcs12.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT,
OPT_TOPK8, OPT_NOITER, OPT_NOCRYPT,
#ifndef OPENSSL_NO_SCRYPT
OPT_SCRYPT, OPT_SCRYPT_N, OPT_SCRYPT_R, OPT_SCRYPT_P,
#endif
OPT_V2, OPT_V1, OPT_V2PRF, OPT_ITER, OPT_PASSIN, OPT_PASSOUT,
OPT_TRADITIONAL,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS pkcs8_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"v1", OPT_V1, 's', "Use PKCS#5 v1.5 and cipher"},
{"v2", OPT_V2, 's', "Use PKCS#5 v2.0 and cipher"},
{"v2prf", OPT_V2PRF, 's', "Set the PRF algorithm to use with PKCS#5 v2.0"},
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"inform", OPT_INFORM, 'F', "Input format (DER or PEM)"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"nocrypt", OPT_NOCRYPT, '-', "Use or expect unencrypted private key"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'F', "Output format (DER or PEM)"},
{"topk8", OPT_TOPK8, '-', "Output PKCS8 file"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
{"traditional", OPT_TRADITIONAL, '-', "use traditional format private key"},
{"iter", OPT_ITER, 'p', "Specify the iteration count"},
{"noiter", OPT_NOITER, '-', "Use 1 as iteration count"},
#ifndef OPENSSL_NO_SCRYPT
OPT_SECTION("Scrypt"),
{"scrypt", OPT_SCRYPT, '-', "Use scrypt algorithm"},
{"scrypt_N", OPT_SCRYPT_N, 's', "Set scrypt N parameter"},
{"scrypt_r", OPT_SCRYPT_R, 's', "Set scrypt r parameter"},
{"scrypt_p", OPT_SCRYPT_P, 's', "Set scrypt p parameter"},
#endif
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
{NULL}
};
int pkcs8_main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL;
ENGINE *e = NULL;
EVP_PKEY *pkey = NULL;
PKCS8_PRIV_KEY_INFO *p8inf = NULL;
X509_SIG *p8 = NULL;
EVP_CIPHER *cipher = NULL;
char *infile = NULL, *outfile = NULL, *ciphername = NULL;
char *passinarg = NULL, *passoutarg = NULL, *prog;
#ifndef OPENSSL_NO_UI_CONSOLE
char pass[APP_PASS_LEN];
#endif
char *passin = NULL, *passout = NULL, *p8pass = NULL;
OPTION_CHOICE o;
int nocrypt = 0, ret = 1, iter = PKCS12_DEFAULT_ITER;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, topk8 = 0, pbe_nid = -1;
int private = 0, traditional = 0;
#ifndef OPENSSL_NO_SCRYPT
long scrypt_N = 0, scrypt_r = 0, scrypt_p = 0;
#endif
prog = opt_init(argc, argv, pkcs8_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(pkcs8_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_TOPK8:
topk8 = 1;
break;
case OPT_NOITER:
iter = 1;
break;
case OPT_NOCRYPT:
nocrypt = 1;
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_TRADITIONAL:
traditional = 1;
break;
case OPT_V2:
ciphername = opt_arg();
break;
case OPT_V1:
pbe_nid = OBJ_txt2nid(opt_arg());
if (pbe_nid == NID_undef) {
BIO_printf(bio_err,
"%s: Unknown PBE algorithm %s\n", prog, opt_arg());
goto opthelp;
}
break;
case OPT_V2PRF:
pbe_nid = OBJ_txt2nid(opt_arg());
if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) {
BIO_printf(bio_err,
"%s: Unknown PRF algorithm %s\n", prog, opt_arg());
goto opthelp;
}
if (cipher == NULL)
cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
break;
case OPT_ITER:
iter = opt_int_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
#ifndef OPENSSL_NO_SCRYPT
case OPT_SCRYPT:
scrypt_N = 16384;
scrypt_r = 8;
scrypt_p = 1;
if (cipher == NULL)
cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
break;
case OPT_SCRYPT_N:
if (!opt_long(opt_arg(), &scrypt_N) || scrypt_N <= 0)
goto opthelp;
break;
case OPT_SCRYPT_R:
if (!opt_long(opt_arg(), &scrypt_r) || scrypt_r <= 0)
goto opthelp;
break;
case OPT_SCRYPT_P:
if (!opt_long(opt_arg(), &scrypt_p) || scrypt_p <= 0)
goto opthelp;
break;
#endif
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
private = 1;
if (!app_RAND_load())
goto end;
if (ciphername != NULL) {
if (!opt_cipher(ciphername, &cipher))
goto opthelp;
}
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if ((pbe_nid == -1) && cipher == NULL)
cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
in = bio_open_default(infile, 'r',
informat == FORMAT_UNDEF ? FORMAT_PEM : informat);
if (in == NULL)
goto end;
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (topk8) {
pkey = load_key(infile, informat, 1, passin, e, "key");
if (pkey == NULL)
goto end;
if ((p8inf = EVP_PKEY2PKCS8(pkey)) == NULL) {
BIO_printf(bio_err, "Error converting key\n");
ERR_print_errors(bio_err);
goto end;
}
if (nocrypt) {
assert(private);
if (outformat == FORMAT_PEM) {
PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
} else if (outformat == FORMAT_ASN1) {
i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
} else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
} else {
X509_ALGOR *pbe;
if (cipher) {
#ifndef OPENSSL_NO_SCRYPT
if (scrypt_N && scrypt_r && scrypt_p)
pbe = PKCS5_pbe2_set_scrypt(cipher, NULL, 0, NULL,
scrypt_N, scrypt_r, scrypt_p);
else
#endif
pbe = PKCS5_pbe2_set_iv(cipher, iter, NULL, 0, NULL,
pbe_nid);
} else {
pbe = PKCS5_pbe_set(pbe_nid, iter, NULL, 0);
}
if (pbe == NULL) {
BIO_printf(bio_err, "Error setting PBE algorithm\n");
ERR_print_errors(bio_err);
goto end;
}
if (passout != NULL) {
p8pass = passout;
} else if (1) {
/* To avoid bit rot */
#ifndef OPENSSL_NO_UI_CONSOLE
p8pass = pass;
if (EVP_read_pw_string
(pass, sizeof(pass), "Enter Encryption Password:", 1)) {
X509_ALGOR_free(pbe);
goto end;
}
} else {
#endif
BIO_printf(bio_err, "Password required\n");
goto end;
}
p8 = PKCS8_set0_pbe(p8pass, strlen(p8pass), p8inf, pbe);
if (p8 == NULL) {
X509_ALGOR_free(pbe);
BIO_printf(bio_err, "Error encrypting key\n");
ERR_print_errors(bio_err);
goto end;
}
assert(private);
if (outformat == FORMAT_PEM)
PEM_write_bio_PKCS8(out, p8);
else if (outformat == FORMAT_ASN1)
i2d_PKCS8_bio(out, p8);
else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
}
ret = 0;
goto end;
}
if (nocrypt) {
if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) {
p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
} else if (informat == FORMAT_ASN1) {
p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
} else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
} else {
if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) {
p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
} else if (informat == FORMAT_ASN1) {
p8 = d2i_PKCS8_bio(in, NULL);
} else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
if (p8 == NULL) {
BIO_printf(bio_err, "Error reading key\n");
ERR_print_errors(bio_err);
goto end;
}
if (passin != NULL) {
p8pass = passin;
} else if (1) {
#ifndef OPENSSL_NO_UI_CONSOLE
p8pass = pass;
if (EVP_read_pw_string(pass, sizeof(pass), "Enter Password:", 0)) {
BIO_printf(bio_err, "Can't read Password\n");
goto end;
}
} else {
#endif
BIO_printf(bio_err, "Password required\n");
goto end;
}
p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
}
if (p8inf == NULL) {
BIO_printf(bio_err, "Error decrypting key\n");
ERR_print_errors(bio_err);
goto end;
}
if ((pkey = EVP_PKCS82PKEY(p8inf)) == NULL) {
BIO_printf(bio_err, "Error converting key\n");
ERR_print_errors(bio_err);
goto end;
}
assert(private);
if (outformat == FORMAT_PEM) {
if (traditional)
PEM_write_bio_PrivateKey_traditional(out, pkey, NULL, NULL, 0,
NULL, passout);
else
PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
} else if (outformat == FORMAT_ASN1) {
i2d_PrivateKey_bio(out, pkey);
} else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
ret = 0;
end:
X509_SIG_free(p8);
PKCS8_PRIV_KEY_INFO_free(p8inf);
EVP_PKEY_free(pkey);
EVP_CIPHER_free(cipher);
release_engine(e);
BIO_free_all(out);
BIO_free(in);
OPENSSL_free(passin);
OPENSSL_free(passout);
return ret;
}
| 12,070 | 30.682415 | 81 |
c
|
openssl
|
openssl-master/apps/pkey.c
|
/*
* Copyright 2006-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include "ec_common.h"
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE,
OPT_IN, OPT_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_TEXT_PUB,
OPT_TEXT, OPT_NOOUT, OPT_CIPHER, OPT_TRADITIONAL, OPT_CHECK, OPT_PUB_CHECK,
OPT_EC_PARAM_ENC, OPT_EC_CONV_FORM,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS pkey_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_PROV_OPTIONS,
{"check", OPT_CHECK, '-', "Check key consistency"},
{"pubcheck", OPT_PUB_CHECK, '-', "Check public key consistency"},
OPT_SECTION("Input"),
{"in", OPT_IN, 's', "Input key"},
{"inform", OPT_INFORM, 'f',
"Key input format (ENGINE, other values ignored)"},
{"passin", OPT_PASSIN, 's', "Key input pass phrase source"},
{"pubin", OPT_PUBIN, '-',
"Read only public components from key input"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file for encoded and/or text output"},
{"outform", OPT_OUTFORM, 'F', "Output encoding format (DER or PEM)"},
{"", OPT_CIPHER, '-', "Any supported cipher to be used for encryption"},
{"passout", OPT_PASSOUT, 's', "Output PEM file pass phrase source"},
{"traditional", OPT_TRADITIONAL, '-',
"Use traditional format for private key PEM output"},
{"pubout", OPT_PUBOUT, '-', "Restrict encoded output to public components"},
{"noout", OPT_NOOUT, '-', "Do not output the key in encoded form"},
{"text", OPT_TEXT, '-', "Output key components in plaintext"},
{"text_pub", OPT_TEXT_PUB, '-',
"Output only public key components in text form"},
{"ec_conv_form", OPT_EC_CONV_FORM, 's',
"Specifies the EC point conversion form in the encoding"},
{"ec_param_enc", OPT_EC_PARAM_ENC, 's',
"Specifies the way the EC parameters are encoded"},
{NULL}
};
int pkey_main(int argc, char **argv)
{
BIO *out = NULL;
ENGINE *e = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
EVP_CIPHER *cipher = NULL;
char *infile = NULL, *outfile = NULL, *passin = NULL, *passout = NULL;
char *passinarg = NULL, *passoutarg = NULL, *ciphername = NULL, *prog;
OPTION_CHOICE o;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM;
int pubin = 0, pubout = 0, text_pub = 0, text = 0, noout = 0, ret = 1;
int private = 0, traditional = 0, check = 0, pub_check = 0;
#ifndef OPENSSL_NO_EC
char *asn1_encoding = NULL;
char *point_format = NULL;
#endif
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, pkey_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(pkey_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
goto opthelp;
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PUBIN:
pubin = pubout = 1;
break;
case OPT_PUBOUT:
pubout = 1;
break;
case OPT_TEXT_PUB:
text_pub = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_TRADITIONAL:
traditional = 1;
break;
case OPT_CHECK:
check = 1;
break;
case OPT_PUB_CHECK:
pub_check = 1;
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_EC_CONV_FORM:
#ifdef OPENSSL_NO_EC
goto opthelp;
#else
point_format = opt_arg();
if (!opt_string(point_format, point_format_options))
goto opthelp;
break;
#endif
case OPT_EC_PARAM_ENC:
#ifdef OPENSSL_NO_EC
goto opthelp;
#else
asn1_encoding = opt_arg();
if (!opt_string(asn1_encoding, asn1_encoding_options))
goto opthelp;
break;
#endif
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (text && text_pub)
BIO_printf(bio_err,
"Warning: The -text option is ignored with -text_pub\n");
if (traditional && (noout || outformat != FORMAT_PEM))
BIO_printf(bio_err,
"Warning: The -traditional is ignored since there is no PEM output\n");
/* -pubout and -text is the same as -text_pub */
if (!text_pub && pubout && text) {
text = 0;
text_pub = 1;
}
private = (!noout && !pubout) || (text && !text_pub);
if (!opt_cipher(ciphername, &cipher))
goto opthelp;
if (cipher == NULL) {
if (passoutarg != NULL)
BIO_printf(bio_err,
"Warning: The -passout option is ignored without a cipher option\n");
} else {
if (noout || outformat != FORMAT_PEM) {
BIO_printf(bio_err,
"Error: Cipher options are supported only for PEM output\n");
goto end;
}
}
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (pubin)
pkey = load_pubkey(infile, informat, 1, passin, e, "Public Key");
else
pkey = load_key(infile, informat, 1, passin, e, "key");
if (pkey == NULL)
goto end;
#ifndef OPENSSL_NO_EC
if (asn1_encoding != NULL || point_format != NULL) {
OSSL_PARAM params[3], *p = params;
if (!EVP_PKEY_is_a(pkey, "EC"))
goto end;
if (asn1_encoding != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING,
asn1_encoding, 0);
if (point_format != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(
OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
point_format, 0);
*p = OSSL_PARAM_construct_end();
if (EVP_PKEY_set_params(pkey, params) <= 0)
goto end;
}
#endif
if (check || pub_check) {
int r;
ctx = EVP_PKEY_CTX_new(pkey, e);
if (ctx == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (check && !pubin)
r = EVP_PKEY_check(ctx);
else
r = EVP_PKEY_public_check(ctx);
if (r == 1) {
BIO_printf(out, "Key is valid\n");
} else {
/*
* Note: at least for RSA keys if this function returns
* -1, there will be no error reasons.
*/
BIO_printf(bio_err, "Key is invalid\n");
ERR_print_errors(bio_err);
goto end;
}
}
if (!noout) {
if (outformat == FORMAT_PEM) {
if (pubout) {
if (!PEM_write_bio_PUBKEY(out, pkey))
goto end;
} else {
assert(private);
if (traditional) {
if (!PEM_write_bio_PrivateKey_traditional(out, pkey, cipher,
NULL, 0, NULL,
passout))
goto end;
} else {
if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
NULL, 0, NULL, passout))
goto end;
}
}
} else if (outformat == FORMAT_ASN1) {
if (text || text_pub) {
BIO_printf(bio_err,
"Error: Text output cannot be combined with DER output\n");
goto end;
}
if (pubout) {
if (!i2d_PUBKEY_bio(out, pkey))
goto end;
} else {
assert(private);
if (!i2d_PrivateKey_bio(out, pkey))
goto end;
}
} else {
BIO_printf(bio_err, "Bad format specified for key\n");
goto end;
}
}
if (text_pub) {
if (EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0)
goto end;
} else if (text) {
assert(private);
if (EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)
goto end;
}
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
EVP_CIPHER_free(cipher);
release_engine(e);
BIO_free_all(out);
OPENSSL_free(passin);
OPENSSL_free(passout);
return ret;
}
| 10,235 | 29.924471 | 92 |
c
|
openssl
|
openssl-master/apps/pkeyparam.c
|
/*
* Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "apps.h"
#include "progs.h"
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/evp.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_IN, OPT_OUT, OPT_TEXT, OPT_NOOUT,
OPT_ENGINE, OPT_CHECK,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS pkeyparam_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"check", OPT_CHECK, '-', "Check key param consistency"},
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"text", OPT_TEXT, '-', "Print parameters as text"},
{"noout", OPT_NOOUT, '-', "Don't output encoded parameters"},
OPT_PROV_OPTIONS,
{NULL}
};
int pkeyparam_main(int argc, char **argv)
{
ENGINE *e = NULL;
BIO *in = NULL, *out = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
int text = 0, noout = 0, ret = EXIT_FAILURE, check = 0, r;
OPTION_CHOICE o;
char *infile = NULL, *outfile = NULL, *prog;
prog = opt_init(argc, argv, pkeyparam_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(pkeyparam_options);
ret = 0;
goto end;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_TEXT:
text = 1;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_CHECK:
check = 1;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
in = bio_open_default(infile, 'r', FORMAT_PEM);
if (in == NULL)
goto end;
out = bio_open_default(outfile, 'w', FORMAT_PEM);
if (out == NULL)
goto end;
pkey = PEM_read_bio_Parameters_ex(in, NULL, app_get0_libctx(),
app_get0_propq());
if (pkey == NULL) {
BIO_printf(bio_err, "Error reading parameters\n");
ERR_print_errors(bio_err);
goto end;
}
if (check) {
if (e == NULL)
ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey,
app_get0_propq());
else
ctx = EVP_PKEY_CTX_new(pkey, e);
if (ctx == NULL) {
ERR_print_errors(bio_err);
goto end;
}
r = EVP_PKEY_param_check(ctx);
if (r == 1) {
BIO_printf(out, "Parameters are valid\n");
} else {
/*
* Note: at least for RSA keys if this function returns
* -1, there will be no error reasons.
*/
BIO_printf(bio_err, "Parameters are invalid\n");
ERR_print_errors(bio_err);
goto end;
}
}
if (!noout)
PEM_write_bio_Parameters(out, pkey);
if (text)
EVP_PKEY_print_params(out, pkey, 0, NULL);
ret = EXIT_SUCCESS;
end:
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
release_engine(e);
BIO_free_all(out);
BIO_free(in);
return ret;
}
| 4,046 | 25.279221 | 74 |
c
|
openssl
|
openssl-master/apps/prime.c
|
/*
* Copyright 2004-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bn.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_HEX, OPT_GENERATE, OPT_BITS, OPT_SAFE, OPT_CHECKS,
OPT_PROV_ENUM
} OPTION_CHOICE;
static int check_num(const char *s, const int is_hex)
{
int i;
/*
* It would make sense to use ossl_isxdigit and ossl_isdigit here,
* but ossl_ctype_check is a local symbol in libcrypto.so.
*/
if (is_hex) {
for (i = 0; ('0' <= s[i] && s[i] <= '9')
|| ('A' <= s[i] && s[i] <= 'F')
|| ('a' <= s[i] && s[i] <= 'f'); i++);
} else {
for (i = 0; '0' <= s[i] && s[i] <= '9'; i++);
}
return s[i] == 0;
}
const OPTIONS prime_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [number...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"bits", OPT_BITS, 'p', "Size of number in bits"},
{"checks", OPT_CHECKS, 'p', "Number of checks"},
OPT_SECTION("Output"),
{"hex", OPT_HEX, '-', "Hex output"},
{"generate", OPT_GENERATE, '-', "Generate a prime"},
{"safe", OPT_SAFE, '-',
"When used with -generate, generate a safe prime"},
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"number", 0, 0, "Number(s) to check for primality if not generating"},
{NULL}
};
int prime_main(int argc, char **argv)
{
BIGNUM *bn = NULL;
int hex = 0, generate = 0, bits = 0, safe = 0, ret = 1;
char *prog;
OPTION_CHOICE o;
prog = opt_init(argc, argv, prime_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(prime_options);
ret = 0;
goto end;
case OPT_HEX:
hex = 1;
break;
case OPT_GENERATE:
generate = 1;
break;
case OPT_BITS:
bits = atoi(opt_arg());
break;
case OPT_SAFE:
safe = 1;
break;
case OPT_CHECKS:
/* ignore parameter and argument */
opt_arg();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Optional arguments are numbers to check. */
if (generate && !opt_check_rest_arg(NULL))
goto opthelp;
argc = opt_num_rest();
argv = opt_rest();
if (!generate && argc == 0) {
BIO_printf(bio_err, "Missing number (s) to check\n");
goto opthelp;
}
if (generate) {
char *s;
if (!bits) {
BIO_printf(bio_err, "Specify the number of bits.\n");
goto end;
}
bn = BN_new();
if (bn == NULL) {
BIO_printf(bio_err, "Out of memory.\n");
goto end;
}
if (!BN_generate_prime_ex(bn, bits, safe, NULL, NULL, NULL)) {
BIO_printf(bio_err, "Failed to generate prime.\n");
goto end;
}
s = hex ? BN_bn2hex(bn) : BN_bn2dec(bn);
if (s == NULL) {
BIO_printf(bio_err, "Out of memory.\n");
goto end;
}
BIO_printf(bio_out, "%s\n", s);
OPENSSL_free(s);
} else {
for ( ; *argv; argv++) {
int r = check_num(argv[0], hex);
if (r)
r = hex ? BN_hex2bn(&bn, argv[0]) : BN_dec2bn(&bn, argv[0]);
if (!r) {
BIO_printf(bio_err, "Failed to process value (%s)\n", argv[0]);
goto end;
}
BN_print(bio_out, bn);
BIO_printf(bio_out, " (%s) %s prime\n",
argv[0],
BN_check_prime(bn, NULL, NULL)
? "is" : "is not");
}
}
ret = 0;
end:
BN_free(bn);
return ret;
}
| 4,327 | 26.05 | 79 |
c
|
openssl
|
openssl-master/apps/rand.c
|
/*
* Copyright 1998-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "apps.h"
#include "progs.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_OUT, OPT_ENGINE, OPT_BASE64, OPT_HEX,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS rand_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] num\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"base64", OPT_BASE64, '-', "Base64 encode output"},
{"hex", OPT_HEX, '-', "Hex encode output"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"num", 0, 0, "Number of bytes to generate"},
{NULL}
};
int rand_main(int argc, char **argv)
{
ENGINE *e = NULL;
BIO *out = NULL;
char *outfile = NULL, *prog;
OPTION_CHOICE o;
int format = FORMAT_BINARY, r, i, ret = 1, buflen = 131072;
long num = -1;
uint8_t *buf = NULL;
prog = opt_init(argc, argv, rand_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(rand_options);
ret = 0;
goto end;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_BASE64:
format = FORMAT_BASE64;
break;
case OPT_HEX:
format = FORMAT_TEXT;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Optional argument is number of bytes to generate. */
argc = opt_num_rest();
argv = opt_rest();
if (argc == 1) {
if (!opt_long(argv[0], &num) || num <= 0)
goto opthelp;
} else if (!opt_check_rest_arg(NULL)) {
goto opthelp;
}
if (!app_RAND_load())
goto end;
out = bio_open_default(outfile, 'w', format);
if (out == NULL)
goto end;
if (format == FORMAT_BASE64) {
BIO *b64 = BIO_new(BIO_f_base64());
if (b64 == NULL)
goto end;
out = BIO_push(b64, out);
}
buf = app_malloc(buflen, "buffer for output file");
while (num > 0) {
long chunk;
chunk = (num > buflen) ? buflen : num;
r = RAND_bytes(buf, chunk);
if (r <= 0)
goto end;
if (format != FORMAT_TEXT) {
if (BIO_write(out, buf, chunk) != chunk)
goto end;
} else {
for (i = 0; i < chunk; i++)
if (BIO_printf(out, "%02x", buf[i]) != 2)
goto end;
}
num -= chunk;
}
if (format == FORMAT_TEXT)
BIO_puts(out, "\n");
if (BIO_flush(out) <= 0)
goto end;
ret = 0;
end:
if (ret != 0)
ERR_print_errors(bio_err);
OPENSSL_free(buf);
release_engine(e);
BIO_free_all(out);
return ret;
}
| 3,755 | 23.874172 | 74 |
c
|
openssl
|
openssl-master/apps/rehash.c
|
/*
* Copyright 2015-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2013-2014 Timo Teräs <[email protected]>
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "apps.h"
#include "progs.h"
#if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
(defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
# include <unistd.h>
# include <stdio.h>
# include <limits.h>
# include <errno.h>
# include <string.h>
# include <ctype.h>
# include <sys/stat.h>
/*
* Make sure that the processing of symbol names is treated the same as when
* libcrypto is built. This is done automatically for public headers (see
* include/openssl/__DECC_INCLUDE_PROLOGUE.H and __DECC_INCLUDE_EPILOGUE.H),
* but not for internal headers.
*/
# ifdef __VMS
# pragma names save
# pragma names as_is,shortened
# endif
# include "internal/o_dir.h"
# ifdef __VMS
# pragma names restore
# endif
# include <openssl/evp.h>
# include <openssl/pem.h>
# include <openssl/x509.h>
# ifndef PATH_MAX
# define PATH_MAX 4096
# endif
# ifndef NAME_MAX
# define NAME_MAX 255
# endif
# define MAX_COLLISIONS 256
# if defined(OPENSSL_SYS_VXWORKS)
/*
* VxWorks has no symbolic links
*/
# define lstat(path, buf) stat(path, buf)
int symlink(const char *target, const char *linkpath)
{
errno = ENOSYS;
return -1;
}
ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
{
errno = ENOSYS;
return -1;
}
# endif
typedef struct hentry_st {
struct hentry_st *next;
char *filename;
unsigned short old_id;
unsigned char need_symlink;
unsigned char digest[EVP_MAX_MD_SIZE];
} HENTRY;
typedef struct bucket_st {
struct bucket_st *next;
HENTRY *first_entry, *last_entry;
unsigned int hash;
unsigned short type;
unsigned short num_needed;
} BUCKET;
enum Type {
/* Keep in sync with |suffixes|, below. */
TYPE_CERT=0, TYPE_CRL=1
};
enum Hash {
HASH_OLD, HASH_NEW, HASH_BOTH
};
static int evpmdsize;
static const EVP_MD *evpmd;
static int remove_links = 1;
static int verbose = 0;
static BUCKET *hash_table[257];
static const char *suffixes[] = { "", "r" };
static const char *extensions[] = { "pem", "crt", "cer", "crl" };
static void bit_set(unsigned char *set, unsigned int bit)
{
set[bit >> 3] |= 1 << (bit & 0x7);
}
static int bit_isset(unsigned char *set, unsigned int bit)
{
return set[bit >> 3] & (1 << (bit & 0x7));
}
/*
* Process an entry; return number of errors.
*/
static int add_entry(enum Type type, unsigned int hash, const char *filename,
const unsigned char *digest, int need_symlink,
unsigned short old_id)
{
static BUCKET nilbucket;
static HENTRY nilhentry;
BUCKET *bp;
HENTRY *ep, *found = NULL;
unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
for (bp = hash_table[ndx]; bp; bp = bp->next)
if (bp->type == type && bp->hash == hash)
break;
if (bp == NULL) {
bp = app_malloc(sizeof(*bp), "hash bucket");
*bp = nilbucket;
bp->next = hash_table[ndx];
bp->type = type;
bp->hash = hash;
hash_table[ndx] = bp;
}
for (ep = bp->first_entry; ep; ep = ep->next) {
if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
BIO_printf(bio_err,
"%s: warning: skipping duplicate %s in %s\n",
opt_getprog(),
type == TYPE_CERT ? "certificate" : "CRL", filename);
return 0;
}
if (strcmp(filename, ep->filename) == 0) {
found = ep;
if (digest == NULL)
break;
}
}
ep = found;
if (ep == NULL) {
if (bp->num_needed >= MAX_COLLISIONS) {
BIO_printf(bio_err,
"%s: error: hash table overflow for %s\n",
opt_getprog(), filename);
return 1;
}
ep = app_malloc(sizeof(*ep), "collision bucket");
*ep = nilhentry;
ep->old_id = ~0;
ep->filename = OPENSSL_strdup(filename);
if (ep->filename == NULL) {
OPENSSL_free(ep);
ep = NULL;
BIO_printf(bio_err, "out of memory\n");
return 1;
}
if (bp->last_entry)
bp->last_entry->next = ep;
if (bp->first_entry == NULL)
bp->first_entry = ep;
bp->last_entry = ep;
}
if (old_id < ep->old_id)
ep->old_id = old_id;
if (need_symlink && !ep->need_symlink) {
ep->need_symlink = 1;
bp->num_needed++;
memcpy(ep->digest, digest, evpmdsize);
}
return 0;
}
/*
* Check if a symlink goes to the right spot; return 0 if okay.
* This can be -1 if bad filename, or an error count.
*/
static int handle_symlink(const char *filename, const char *fullpath)
{
unsigned int hash = 0;
int i, type, id;
unsigned char ch;
char linktarget[PATH_MAX], *endptr;
ossl_ssize_t n;
for (i = 0; i < 8; i++) {
ch = filename[i];
if (!isxdigit(ch))
return -1;
hash <<= 4;
hash += OPENSSL_hexchar2int(ch);
}
if (filename[i++] != '.')
return -1;
for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--)
if (OPENSSL_strncasecmp(&filename[i],
suffixes[type], strlen(suffixes[type])) == 0)
break;
i += strlen(suffixes[type]);
id = strtoul(&filename[i], &endptr, 10);
if (*endptr != '\0')
return -1;
n = readlink(fullpath, linktarget, sizeof(linktarget));
if (n < 0 || n >= (int)sizeof(linktarget))
return -1;
linktarget[n] = 0;
return add_entry(type, hash, linktarget, NULL, 0, id);
}
/*
* process a file, return number of errors.
*/
static int do_file(const char *filename, const char *fullpath, enum Hash h)
{
STACK_OF (X509_INFO) *inf = NULL;
X509_INFO *x;
const X509_NAME *name = NULL;
BIO *b;
const char *ext;
unsigned char digest[EVP_MAX_MD_SIZE];
int type, errs = 0;
size_t i;
/* Does it end with a recognized extension? */
if ((ext = strrchr(filename, '.')) == NULL)
goto end;
for (i = 0; i < OSSL_NELEM(extensions); i++) {
if (OPENSSL_strcasecmp(extensions[i], ext + 1) == 0)
break;
}
if (i >= OSSL_NELEM(extensions))
goto end;
/* Does it have X.509 data in it? */
if ((b = BIO_new_file(fullpath, "r")) == NULL) {
BIO_printf(bio_err, "%s: error: skipping %s, cannot open file\n",
opt_getprog(), filename);
errs++;
goto end;
}
inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
BIO_free(b);
if (inf == NULL)
goto end;
if (sk_X509_INFO_num(inf) != 1) {
BIO_printf(bio_err,
"%s: warning: skipping %s,"
"it does not contain exactly one certificate or CRL\n",
opt_getprog(), filename);
/* This is not an error. */
goto end;
}
x = sk_X509_INFO_value(inf, 0);
if (x->x509 != NULL) {
type = TYPE_CERT;
name = X509_get_subject_name(x->x509);
if (!X509_digest(x->x509, evpmd, digest, NULL)) {
BIO_printf(bio_err, "out of memory\n");
++errs;
goto end;
}
} else if (x->crl != NULL) {
type = TYPE_CRL;
name = X509_CRL_get_issuer(x->crl);
if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) {
BIO_printf(bio_err, "out of memory\n");
++errs;
goto end;
}
} else {
++errs;
goto end;
}
if (name != NULL) {
if (h == HASH_NEW || h == HASH_BOTH) {
int ok;
unsigned long hash_value =
X509_NAME_hash_ex(name,
app_get0_libctx(), app_get0_propq(), &ok);
if (ok) {
errs += add_entry(type, hash_value, filename, digest, 1, ~0);
} else {
BIO_printf(bio_err, "%s: error calculating SHA1 hash value\n",
opt_getprog());
errs++;
}
}
if ((h == HASH_OLD) || (h == HASH_BOTH))
errs += add_entry(type, X509_NAME_hash_old(name),
filename, digest, 1, ~0);
}
end:
sk_X509_INFO_pop_free(inf, X509_INFO_free);
return errs;
}
static void str_free(char *s)
{
OPENSSL_free(s);
}
static int ends_with_dirsep(const char *path)
{
if (*path != '\0')
path += strlen(path) - 1;
# if defined __VMS
if (*path == ']' || *path == '>' || *path == ':')
return 1;
# elif defined _WIN32
if (*path == '\\')
return 1;
# endif
return *path == '/';
}
static int sk_strcmp(const char * const *a, const char * const *b)
{
return strcmp(*a, *b);
}
/*
* Process a directory; return number of errors found.
*/
static int do_dir(const char *dirname, enum Hash h)
{
BUCKET *bp, *nextbp;
HENTRY *ep, *nextep;
OPENSSL_DIR_CTX *d = NULL;
struct stat st;
unsigned char idmask[MAX_COLLISIONS / 8];
int n, numfiles, nextid, buflen, errs = 0;
size_t i;
const char *pathsep;
const char *filename;
char *buf, *copy = NULL;
STACK_OF(OPENSSL_STRING) *files = NULL;
if (app_access(dirname, W_OK) < 0) {
BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
return 1;
}
buflen = strlen(dirname);
pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
buflen += NAME_MAX + 1 + 1;
buf = app_malloc(buflen, "filename buffer");
if (verbose)
BIO_printf(bio_out, "Doing %s\n", dirname);
if ((files = sk_OPENSSL_STRING_new(sk_strcmp)) == NULL) {
BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
errs = 1;
goto err;
}
while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
if ((copy = OPENSSL_strdup(filename)) == NULL
|| sk_OPENSSL_STRING_push(files, copy) == 0) {
OPENSSL_free(copy);
BIO_puts(bio_err, "out of memory\n");
errs = 1;
goto err;
}
}
OPENSSL_DIR_end(&d);
sk_OPENSSL_STRING_sort(files);
numfiles = sk_OPENSSL_STRING_num(files);
for (n = 0; n < numfiles; ++n) {
filename = sk_OPENSSL_STRING_value(files, n);
if (BIO_snprintf(buf, buflen, "%s%s%s",
dirname, pathsep, filename) >= buflen)
continue;
if (lstat(buf, &st) < 0)
continue;
if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
continue;
errs += do_file(filename, buf, h);
}
for (i = 0; i < OSSL_NELEM(hash_table); i++) {
for (bp = hash_table[i]; bp; bp = nextbp) {
nextbp = bp->next;
nextid = 0;
memset(idmask, 0, (bp->num_needed + 7) / 8);
for (ep = bp->first_entry; ep; ep = ep->next)
if (ep->old_id < bp->num_needed)
bit_set(idmask, ep->old_id);
for (ep = bp->first_entry; ep; ep = nextep) {
nextep = ep->next;
if (ep->old_id < bp->num_needed) {
/* Link exists, and is used as-is */
BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
suffixes[bp->type], ep->old_id);
if (verbose)
BIO_printf(bio_out, "link %s -> %s\n",
ep->filename, buf);
} else if (ep->need_symlink) {
/* New link needed (it may replace something) */
while (bit_isset(idmask, nextid))
nextid++;
BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
dirname, pathsep, &n, bp->hash,
suffixes[bp->type], nextid);
if (verbose)
BIO_printf(bio_out, "link %s -> %s\n",
ep->filename, &buf[n]);
if (unlink(buf) < 0 && errno != ENOENT) {
BIO_printf(bio_err,
"%s: Can't unlink %s, %s\n",
opt_getprog(), buf, strerror(errno));
errs++;
}
if (symlink(ep->filename, buf) < 0) {
BIO_printf(bio_err,
"%s: Can't symlink %s, %s\n",
opt_getprog(), ep->filename,
strerror(errno));
errs++;
}
bit_set(idmask, nextid);
} else if (remove_links) {
/* Link to be deleted */
BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
dirname, pathsep, &n, bp->hash,
suffixes[bp->type], ep->old_id);
if (verbose)
BIO_printf(bio_out, "unlink %s\n",
&buf[n]);
if (unlink(buf) < 0 && errno != ENOENT) {
BIO_printf(bio_err,
"%s: Can't unlink %s, %s\n",
opt_getprog(), buf, strerror(errno));
errs++;
}
}
OPENSSL_free(ep->filename);
OPENSSL_free(ep);
}
OPENSSL_free(bp);
}
hash_table[i] = NULL;
}
err:
sk_OPENSSL_STRING_pop_free(files, str_free);
OPENSSL_free(buf);
return errs;
}
typedef enum OPTION_choice {
OPT_COMMON,
OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS rehash_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"h", OPT_HELP, '-', "Display this summary"},
{"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
{"old", OPT_OLD, '-', "Use old-style hash to generate links"},
{"n", OPT_N, '-', "Do not remove existing links"},
OPT_SECTION("Output"),
{"v", OPT_VERBOSE, '-', "Verbose output"},
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"directory", 0, 0, "One or more directories to process (optional)"},
{NULL}
};
int rehash_main(int argc, char **argv)
{
const char *env, *prog;
char *e, *m;
int errs = 0;
OPTION_CHOICE o;
enum Hash h = HASH_NEW;
prog = opt_init(argc, argv, rehash_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(rehash_options);
goto end;
case OPT_COMPAT:
h = HASH_BOTH;
break;
case OPT_OLD:
h = HASH_OLD;
break;
case OPT_N:
remove_links = 0;
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Optional arguments are directories to scan. */
argc = opt_num_rest();
argv = opt_rest();
evpmd = EVP_sha1();
evpmdsize = EVP_MD_get_size(evpmd);
if (*argv != NULL) {
while (*argv != NULL)
errs += do_dir(*argv++, h);
} else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
m = OPENSSL_strdup(env);
for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
errs += do_dir(e, h);
OPENSSL_free(m);
} else {
errs += do_dir(X509_get_default_cert_dir(), h);
}
end:
return errs;
}
#else
const OPTIONS rehash_options[] = {
{NULL}
};
int rehash_main(int argc, char **argv)
{
BIO_printf(bio_err, "Not available; use c_rehash script\n");
return 1;
}
#endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */
| 16,657 | 27.770294 | 78 |
c
|
openssl
|
openssl-master/apps/rsa.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Necessary for legacy RSA public key export */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/encoder.h>
/*
* This include is to get OSSL_KEYMGMT_SELECT_*, which feels a bit
* much just for those macros... they might serve better as EVP macros.
*/
#include <openssl/core_dispatch.h>
#ifndef OPENSSL_NO_RC4
# define DEFAULT_PVK_ENCR_STRENGTH 2
#else
# define DEFAULT_PVK_ENCR_STRENGTH 0
#endif
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT,
OPT_PUBIN, OPT_PUBOUT, OPT_PASSOUT, OPT_PASSIN,
OPT_RSAPUBKEY_IN, OPT_RSAPUBKEY_OUT,
/* Do not change the order here; see case statements below */
OPT_PVK_NONE, OPT_PVK_WEAK, OPT_PVK_STRONG,
OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_CHECK, OPT_CIPHER,
OPT_PROV_ENUM, OPT_TRADITIONAL
} OPTION_CHOICE;
const OPTIONS rsa_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"check", OPT_CHECK, '-', "Verify key consistency"},
{"", OPT_CIPHER, '-', "Any supported cipher"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, 's', "Input file"},
{"inform", OPT_INFORM, 'f', "Input format (DER/PEM/P12/ENGINE)"},
{"pubin", OPT_PUBIN, '-', "Expect a public key in input file"},
{"RSAPublicKey_in", OPT_RSAPUBKEY_IN, '-', "Input is an RSAPublicKey"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'f', "Output format, one of DER PEM PVK"},
{"pubout", OPT_PUBOUT, '-', "Output a public key"},
{"RSAPublicKey_out", OPT_RSAPUBKEY_OUT, '-', "Output is an RSAPublicKey"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
{"noout", OPT_NOOUT, '-', "Don't print key out"},
{"text", OPT_TEXT, '-', "Print the key in text"},
{"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"},
{"traditional", OPT_TRADITIONAL, '-',
"Use traditional format for private keys"},
#ifndef OPENSSL_NO_RC4
OPT_SECTION("PVK"),
{"pvk-strong", OPT_PVK_STRONG, '-', "Enable 'Strong' PVK encoding level (default)"},
{"pvk-weak", OPT_PVK_WEAK, '-', "Enable 'Weak' PVK encoding level"},
{"pvk-none", OPT_PVK_NONE, '-', "Don't enforce PVK encoding"},
#endif
OPT_PROV_OPTIONS,
{NULL}
};
static int try_legacy_encoding(EVP_PKEY *pkey, int outformat, int pubout,
BIO *out)
{
int ret = 0;
#ifndef OPENSSL_NO_DEPRECATED_3_0
const RSA *rsa = EVP_PKEY_get0_RSA(pkey);
if (rsa == NULL)
return 0;
if (outformat == FORMAT_ASN1) {
if (pubout == 2)
ret = i2d_RSAPublicKey_bio(out, rsa) > 0;
else
ret = i2d_RSA_PUBKEY_bio(out, rsa) > 0;
} else if (outformat == FORMAT_PEM) {
if (pubout == 2)
ret = PEM_write_bio_RSAPublicKey(out, rsa) > 0;
else
ret = PEM_write_bio_RSA_PUBKEY(out, rsa) > 0;
# ifndef OPENSSL_NO_DSA
} else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
ret = i2b_PublicKey_bio(out, pkey) > 0;
# endif
}
#endif
return ret;
}
int rsa_main(int argc, char **argv)
{
ENGINE *e = NULL;
BIO *out = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *pctx;
EVP_CIPHER *enc = NULL;
char *infile = NULL, *outfile = NULL, *ciphername = NULL, *prog;
char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL;
int private = 0;
int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, check = 0;
int noout = 0, modulus = 0, pubin = 0, pubout = 0, ret = 1;
int pvk_encr = DEFAULT_PVK_ENCR_STRENGTH;
OPTION_CHOICE o;
int traditional = 0;
const char *output_type = NULL;
const char *output_structure = NULL;
int selection = 0;
OSSL_ENCODER_CTX *ectx = NULL;
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, rsa_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(rsa_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PUBIN:
pubin = 1;
break;
case OPT_PUBOUT:
pubout = 1;
break;
case OPT_RSAPUBKEY_IN:
pubin = 2;
break;
case OPT_RSAPUBKEY_OUT:
pubout = 2;
break;
case OPT_PVK_STRONG: /* pvk_encr:= 2 */
case OPT_PVK_WEAK: /* pvk_encr:= 1 */
case OPT_PVK_NONE: /* pvk_encr:= 0 */
pvk_encr = (o - OPT_PVK_NONE);
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_MODULUS:
modulus = 1;
break;
case OPT_CHECK:
check = 1;
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_TRADITIONAL:
traditional = 1;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!opt_cipher(ciphername, &enc))
goto opthelp;
private = (text && !pubin) || (!pubout && !noout);
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if (check && pubin) {
BIO_printf(bio_err, "Only private keys can be checked\n");
goto end;
}
if (pubin) {
int tmpformat = FORMAT_UNDEF;
if (pubin == 2) {
if (informat == FORMAT_PEM)
tmpformat = FORMAT_PEMRSA;
else if (informat == FORMAT_ASN1)
tmpformat = FORMAT_ASN1RSA;
} else {
tmpformat = informat;
}
pkey = load_pubkey(infile, tmpformat, 1, passin, e, "public key");
} else {
pkey = load_key(infile, informat, 1, passin, e, "private key");
}
if (pkey == NULL) {
ERR_print_errors(bio_err);
goto end;
}
if (!EVP_PKEY_is_a(pkey, "RSA") && !EVP_PKEY_is_a(pkey, "RSA-PSS")) {
BIO_printf(bio_err, "Not an RSA key\n");
goto end;
}
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (text) {
assert(pubin || private);
if ((pubin && EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0)
|| (!pubin && EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)) {
perror(outfile);
ERR_print_errors(bio_err);
goto end;
}
}
if (modulus) {
BIGNUM *n = NULL;
/* Every RSA key has an 'n' */
EVP_PKEY_get_bn_param(pkey, "n", &n);
BIO_printf(out, "Modulus=");
BN_print(out, n);
BIO_printf(out, "\n");
BN_free(n);
}
if (check) {
int r;
pctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL);
if (pctx == NULL) {
BIO_printf(bio_err, "RSA unable to create PKEY context\n");
ERR_print_errors(bio_err);
goto end;
}
r = EVP_PKEY_check(pctx);
EVP_PKEY_CTX_free(pctx);
if (r == 1) {
BIO_printf(out, "RSA key ok\n");
} else if (r == 0) {
BIO_printf(bio_err, "RSA key not ok\n");
ERR_print_errors(bio_err);
} else if (r < 0) {
ERR_print_errors(bio_err);
goto end;
}
}
if (noout) {
ret = 0;
goto end;
}
BIO_printf(bio_err, "writing RSA key\n");
/* Choose output type for the format */
if (outformat == FORMAT_ASN1) {
output_type = "DER";
} else if (outformat == FORMAT_PEM) {
output_type = "PEM";
} else if (outformat == FORMAT_MSBLOB) {
output_type = "MSBLOB";
} else if (outformat == FORMAT_PVK) {
if (pubin) {
BIO_printf(bio_err, "PVK form impossible with public key input\n");
goto end;
}
output_type = "PVK";
} else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
/* Select what you want in the output */
if (pubout || pubin) {
selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
} else {
assert(private);
selection = (OSSL_KEYMGMT_SELECT_KEYPAIR
| OSSL_KEYMGMT_SELECT_ALL_PARAMETERS);
}
/* For DER based output, select the desired output structure */
if (outformat == FORMAT_ASN1 || outformat == FORMAT_PEM) {
if (pubout || pubin) {
if (pubout == 2)
output_structure = "pkcs1"; /* "type-specific" would work too */
else
output_structure = "SubjectPublicKeyInfo";
} else {
assert(private);
if (traditional)
output_structure = "pkcs1"; /* "type-specific" would work too */
else
output_structure = "PrivateKeyInfo";
}
}
/* Now, perform the encoding */
ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection,
output_type, output_structure,
NULL);
if (OSSL_ENCODER_CTX_get_num_encoders(ectx) == 0) {
if ((!pubout && !pubin)
|| !try_legacy_encoding(pkey, outformat, pubout, out))
BIO_printf(bio_err, "%s format not supported\n", output_type);
else
ret = 0;
goto end;
}
/* Passphrase setup */
if (enc != NULL)
OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL);
/* Default passphrase prompter */
if (enc != NULL || outformat == FORMAT_PVK) {
OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL);
if (passout != NULL)
/* When passout given, override the passphrase prompter */
OSSL_ENCODER_CTX_set_passphrase(ectx,
(const unsigned char *)passout,
strlen(passout));
}
/* PVK is a bit special... */
if (outformat == FORMAT_PVK) {
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_int("encrypt-level", &pvk_encr);
if (!OSSL_ENCODER_CTX_set_params(ectx, params)) {
BIO_printf(bio_err, "invalid PVK encryption level\n");
goto end;
}
}
if (!OSSL_ENCODER_to_bio(ectx, out)) {
BIO_printf(bio_err, "unable to write key\n");
ERR_print_errors(bio_err);
goto end;
}
ret = 0;
end:
OSSL_ENCODER_CTX_free(ectx);
release_engine(e);
BIO_free_all(out);
EVP_PKEY_free(pkey);
EVP_CIPHER_free(enc);
OPENSSL_free(passin);
OPENSSL_free(passout);
return ret;
}
| 12,590 | 29.413043 | 88 |
c
|
openssl
|
openssl-master/apps/rsautl.c
|
/*
* Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include "apps.h"
#include "progs.h"
#include <string.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#define RSA_SIGN 1
#define RSA_VERIFY 2
#define RSA_ENCRYPT 3
#define RSA_DECRYPT 4
#define KEY_PRIVKEY 1
#define KEY_PUBKEY 2
#define KEY_CERT 3
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ENGINE, OPT_IN, OPT_OUT, OPT_ASN1PARSE, OPT_HEXDUMP,
OPT_RSA_RAW, OPT_OAEP, OPT_PKCS, OPT_X931,
OPT_SIGN, OPT_VERIFY, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT,
OPT_PUBIN, OPT_CERTIN, OPT_INKEY, OPT_PASSIN, OPT_KEYFORM,
OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS rsautl_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"sign", OPT_SIGN, '-', "Sign with private key"},
{"verify", OPT_VERIFY, '-', "Verify with public key"},
{"encrypt", OPT_ENCRYPT, '-', "Encrypt with public key"},
{"decrypt", OPT_DECRYPT, '-', "Decrypt with private key"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"inkey", OPT_INKEY, 's', "Input key, by default an RSA private key"},
{"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"},
{"pubin", OPT_PUBIN, '-', "Input key is an RSA public pkey"},
{"certin", OPT_CERTIN, '-', "Input is a cert carrying an RSA public key"},
{"rev", OPT_REV, '-', "Reverse the order of the input buffer"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file"},
{"raw", OPT_RSA_RAW, '-', "Use no padding"},
{"pkcs", OPT_PKCS, '-', "Use PKCS#1 v1.5 padding (default)"},
{"x931", OPT_X931, '-', "Use ANSI X9.31 padding"},
{"oaep", OPT_OAEP, '-', "Use PKCS#1 OAEP"},
{"asn1parse", OPT_ASN1PARSE, '-',
"Run output through asn1parse; useful with -verify"},
{"hexdump", OPT_HEXDUMP, '-', "Hex dump output"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
{NULL}
};
int rsautl_main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL;
ENGINE *e = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
X509 *x;
char *infile = NULL, *outfile = NULL, *keyfile = NULL;
char *passinarg = NULL, *passin = NULL, *prog;
char rsa_mode = RSA_VERIFY, key_type = KEY_PRIVKEY;
unsigned char *rsa_in = NULL, *rsa_out = NULL, pad = RSA_PKCS1_PADDING;
size_t rsa_inlen, rsa_outlen = 0;
int keyformat = FORMAT_UNDEF, keysize, ret = 1, rv;
int hexdump = 0, asn1parse = 0, need_priv = 0, rev = 0;
OPTION_CHOICE o;
prog = opt_init(argc, argv, rsautl_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(rsautl_options);
ret = 0;
goto end;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_ASN1PARSE:
asn1parse = 1;
break;
case OPT_HEXDUMP:
hexdump = 1;
break;
case OPT_RSA_RAW:
pad = RSA_NO_PADDING;
break;
case OPT_OAEP:
pad = RSA_PKCS1_OAEP_PADDING;
break;
case OPT_PKCS:
pad = RSA_PKCS1_PADDING;
break;
case OPT_X931:
pad = RSA_X931_PADDING;
break;
case OPT_SIGN:
rsa_mode = RSA_SIGN;
need_priv = 1;
break;
case OPT_VERIFY:
rsa_mode = RSA_VERIFY;
break;
case OPT_REV:
rev = 1;
break;
case OPT_ENCRYPT:
rsa_mode = RSA_ENCRYPT;
break;
case OPT_DECRYPT:
rsa_mode = RSA_DECRYPT;
need_priv = 1;
break;
case OPT_PUBIN:
key_type = KEY_PUBKEY;
break;
case OPT_CERTIN:
key_type = KEY_CERT;
break;
case OPT_INKEY:
keyfile = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!app_RAND_load())
goto end;
if (need_priv && (key_type != KEY_PRIVKEY)) {
BIO_printf(bio_err, "A private key is needed for this operation\n");
goto end;
}
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
switch (key_type) {
case KEY_PRIVKEY:
pkey = load_key(keyfile, keyformat, 0, passin, e, "private key");
break;
case KEY_PUBKEY:
pkey = load_pubkey(keyfile, keyformat, 0, NULL, e, "public key");
break;
case KEY_CERT:
x = load_cert(keyfile, FORMAT_UNDEF, "Certificate");
if (x) {
pkey = X509_get_pubkey(x);
X509_free(x);
}
break;
}
if (pkey == NULL)
return 1;
in = bio_open_default(infile, 'r', FORMAT_BINARY);
if (in == NULL)
goto end;
out = bio_open_default(outfile, 'w', FORMAT_BINARY);
if (out == NULL)
goto end;
keysize = EVP_PKEY_get_size(pkey);
rsa_in = app_malloc(keysize * 2, "hold rsa key");
rsa_out = app_malloc(keysize, "output rsa key");
rsa_outlen = keysize;
/* Read the input data */
rv = BIO_read(in, rsa_in, keysize * 2);
if (rv < 0) {
BIO_printf(bio_err, "Error reading input Data\n");
goto end;
}
rsa_inlen = rv;
if (rev) {
size_t i;
unsigned char ctmp;
for (i = 0; i < rsa_inlen / 2; i++) {
ctmp = rsa_in[i];
rsa_in[i] = rsa_in[rsa_inlen - 1 - i];
rsa_in[rsa_inlen - 1 - i] = ctmp;
}
}
if ((ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL)) == NULL)
goto end;
switch (rsa_mode) {
case RSA_VERIFY:
rv = EVP_PKEY_verify_recover_init(ctx) > 0
&& EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0
&& EVP_PKEY_verify_recover(ctx, rsa_out, &rsa_outlen,
rsa_in, rsa_inlen) > 0;
break;
case RSA_SIGN:
rv = EVP_PKEY_sign_init(ctx) > 0
&& EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0
&& EVP_PKEY_sign(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0;
break;
case RSA_ENCRYPT:
rv = EVP_PKEY_encrypt_init(ctx) > 0
&& EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0
&& EVP_PKEY_encrypt(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0;
break;
case RSA_DECRYPT:
rv = EVP_PKEY_decrypt_init(ctx) > 0
&& EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0
&& EVP_PKEY_decrypt(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0;
break;
}
if (!rv) {
BIO_printf(bio_err, "RSA operation error\n");
ERR_print_errors(bio_err);
goto end;
}
ret = 0;
if (asn1parse) {
if (!ASN1_parse_dump(out, rsa_out, rsa_outlen, 1, -1)) {
ERR_print_errors(bio_err);
}
} else if (hexdump) {
BIO_dump(out, (char *)rsa_out, rsa_outlen);
} else {
BIO_write(out, rsa_out, rsa_outlen);
}
end:
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
release_engine(e);
BIO_free(in);
BIO_free_all(out);
OPENSSL_free(rsa_in);
OPENSSL_free(rsa_out);
OPENSSL_free(passin);
return ret;
}
| 8,636 | 28.477816 | 87 |
c
|
openssl
|
openssl-master/apps/s_time.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_SOCK
#include "apps.h"
#include "progs.h"
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include "s_apps.h"
#include <openssl/err.h>
#include "internal/sockets.h"
#if !defined(OPENSSL_SYS_MSDOS)
# include <unistd.h>
#endif
#define SSL_CONNECT_NAME "localhost:4433"
#define SECONDS 30
#define SECONDSSTR "30"
static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx);
/*
* Define a HTTP get command globally.
* Also define the size of the command, this is two bytes less than
* the size of the string because the %s is replaced by the URL.
*/
static const char fmt_http_get_cmd[] = "GET %s HTTP/1.0\r\n\r\n";
static const size_t fmt_http_get_cmd_size = sizeof(fmt_http_get_cmd) - 2;
typedef enum OPTION_choice {
OPT_COMMON,
OPT_CONNECT, OPT_CIPHER, OPT_CIPHERSUITES, OPT_CERT, OPT_NAMEOPT, OPT_KEY,
OPT_CAPATH, OPT_CAFILE, OPT_CASTORE,
OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
OPT_NEW, OPT_REUSE, OPT_BUGS, OPT_VERIFY, OPT_TIME, OPT_SSL3,
OPT_WWW, OPT_TLS1, OPT_TLS1_1, OPT_TLS1_2, OPT_TLS1_3,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS s_time_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("Connection"),
{"connect", OPT_CONNECT, 's',
"Where to connect as post:port (default is " SSL_CONNECT_NAME ")"},
{"new", OPT_NEW, '-', "Just time new connections"},
{"reuse", OPT_REUSE, '-', "Just time connection reuse"},
{"bugs", OPT_BUGS, '-', "Turn on SSL bug compatibility"},
{"cipher", OPT_CIPHER, 's', "TLSv1.2 and below cipher list to be used"},
{"ciphersuites", OPT_CIPHERSUITES, 's',
"Specify TLSv1.3 ciphersuites to be used"},
#ifndef OPENSSL_NO_SSL3
{"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
#endif
#ifndef OPENSSL_NO_TLS1
{"tls1", OPT_TLS1, '-', "Just use TLSv1.0"},
#endif
#ifndef OPENSSL_NO_TLS1_1
{"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
#endif
#ifndef OPENSSL_NO_TLS1_2
{"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
#endif
#ifndef OPENSSL_NO_TLS1_3
{"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"},
#endif
{"verify", OPT_VERIFY, 'p',
"Turn on peer certificate verification, set depth"},
{"time", OPT_TIME, 'p', "Seconds to collect data, default " SECONDSSTR},
{"www", OPT_WWW, 's', "Fetch specified page from the site"},
OPT_SECTION("Certificate"),
{"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
{"cert", OPT_CERT, '<', "Cert file to use, PEM format assumed"},
{"key", OPT_KEY, '<', "File with key, PEM; default is -cert file"},
{"cafile", OPT_CAFILE, '<', "PEM format file of CA's"},
{"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
{"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
{"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
{"no-CAfile", OPT_NOCAFILE, '-',
"Do not load the default certificates file"},
{"no-CApath", OPT_NOCAPATH, '-',
"Do not load certificates from the default certificates directory"},
{"no-CAstore", OPT_NOCASTORE, '-',
"Do not load certificates from the default certificates store URI"},
OPT_PROV_OPTIONS,
{NULL}
};
#define START 0
#define STOP 1
static double tm_Time_F(int s)
{
return app_tminterval(s, 1);
}
int s_time_main(int argc, char **argv)
{
char buf[1024 * 8];
SSL *scon = NULL;
SSL_CTX *ctx = NULL;
const SSL_METHOD *meth = NULL;
char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
char *cipher = NULL, *ciphersuites = NULL;
char *www_path = NULL;
char *host = SSL_CONNECT_NAME, *certfile = NULL, *keyfile = NULL, *prog;
double totalTime = 0.0;
int noCApath = 0, noCAfile = 0, noCAstore = 0;
int maxtime = SECONDS, nConn = 0, perform = 3, ret = 1, i, st_bugs = 0;
long bytes_read = 0, finishtime = 0;
OPTION_CHOICE o;
int min_version = 0, max_version = 0, ver, buf_len, fd;
size_t buf_size;
meth = TLS_client_method();
prog = opt_init(argc, argv, s_time_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(s_time_options);
ret = 0;
goto end;
case OPT_CONNECT:
host = opt_arg();
break;
case OPT_REUSE:
perform = 2;
break;
case OPT_NEW:
perform = 1;
break;
case OPT_VERIFY:
verify_args.depth = opt_int_arg();
BIO_printf(bio_err, "%s: verify depth is %d\n",
prog, verify_args.depth);
break;
case OPT_CERT:
certfile = opt_arg();
break;
case OPT_NAMEOPT:
if (!set_nameopt(opt_arg()))
goto end;
break;
case OPT_KEY:
keyfile = opt_arg();
break;
case OPT_CAPATH:
CApath = opt_arg();
break;
case OPT_CAFILE:
CAfile = opt_arg();
break;
case OPT_NOCAPATH:
noCApath = 1;
break;
case OPT_NOCAFILE:
noCAfile = 1;
break;
case OPT_CASTORE:
CAstore = opt_arg();
break;
case OPT_NOCASTORE:
noCAstore = 1;
break;
case OPT_CIPHER:
cipher = opt_arg();
break;
case OPT_CIPHERSUITES:
ciphersuites = opt_arg();
break;
case OPT_BUGS:
st_bugs = 1;
break;
case OPT_TIME:
maxtime = opt_int_arg();
break;
case OPT_WWW:
www_path = opt_arg();
buf_size = strlen(www_path) + fmt_http_get_cmd_size;
if (buf_size > sizeof(buf)) {
BIO_printf(bio_err, "%s: -www option is too long\n", prog);
goto end;
}
break;
case OPT_SSL3:
min_version = SSL3_VERSION;
max_version = SSL3_VERSION;
break;
case OPT_TLS1:
min_version = TLS1_VERSION;
max_version = TLS1_VERSION;
break;
case OPT_TLS1_1:
min_version = TLS1_1_VERSION;
max_version = TLS1_1_VERSION;
break;
case OPT_TLS1_2:
min_version = TLS1_2_VERSION;
max_version = TLS1_2_VERSION;
break;
case OPT_TLS1_3:
min_version = TLS1_3_VERSION;
max_version = TLS1_3_VERSION;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (cipher == NULL)
cipher = getenv("SSL_CIPHER");
if ((ctx = SSL_CTX_new(meth)) == NULL)
goto end;
SSL_CTX_set_quiet_shutdown(ctx, 1);
if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
goto end;
if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
goto end;
if (st_bugs)
SSL_CTX_set_options(ctx, SSL_OP_ALL);
if (cipher != NULL && !SSL_CTX_set_cipher_list(ctx, cipher))
goto end;
if (ciphersuites != NULL && !SSL_CTX_set_ciphersuites(ctx, ciphersuites))
goto end;
if (!set_cert_stuff(ctx, certfile, keyfile))
goto end;
if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore)) {
ERR_print_errors(bio_err);
goto end;
}
if (!(perform & 1))
goto next;
printf("Collecting connection statistics for %d seconds\n", maxtime);
/* Loop and time how long it takes to make connections */
bytes_read = 0;
finishtime = (long)time(NULL) + maxtime;
tm_Time_F(START);
for (;;) {
if (finishtime < (long)time(NULL))
break;
if ((scon = doConnection(NULL, host, ctx)) == NULL)
goto end;
if (www_path != NULL) {
buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd,
www_path);
if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0)
goto end;
while ((i = SSL_read(scon, buf, sizeof(buf))) > 0)
bytes_read += i;
}
SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
BIO_closesocket(SSL_get_fd(scon));
nConn += 1;
if (SSL_session_reused(scon)) {
ver = 'r';
} else {
ver = SSL_version(scon);
if (ver == TLS1_VERSION)
ver = 't';
else if (ver == SSL3_VERSION)
ver = '3';
else
ver = '*';
}
fputc(ver, stdout);
fflush(stdout);
SSL_free(scon);
scon = NULL;
}
totalTime += tm_Time_F(STOP); /* Add the time for this iteration */
i = (int)((long)time(NULL) - finishtime + maxtime);
printf
("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n",
nConn, totalTime, ((double)nConn / totalTime), bytes_read);
printf
("%d connections in %ld real seconds, %ld bytes read per connection\n",
nConn, (long)time(NULL) - finishtime + maxtime,
nConn > 0 ? bytes_read / nConn : 0l);
/*
* Now loop and time connections using the same session id over and over
*/
next:
if (!(perform & 2))
goto end;
printf("\n\nNow timing with session id reuse.\n");
/* Get an SSL object so we can reuse the session id */
if ((scon = doConnection(NULL, host, ctx)) == NULL) {
BIO_printf(bio_err, "Unable to get connection\n");
goto end;
}
if (www_path != NULL) {
buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path);
if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0)
goto end;
while ((i = SSL_read(scon, buf, sizeof(buf))) > 0)
continue;
}
SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
if ((fd = SSL_get_fd(scon)) >= 0)
BIO_closesocket(fd);
nConn = 0;
totalTime = 0.0;
finishtime = (long)time(NULL) + maxtime;
printf("starting\n");
bytes_read = 0;
tm_Time_F(START);
for (;;) {
if (finishtime < (long)time(NULL))
break;
if ((doConnection(scon, host, ctx)) == NULL)
goto end;
if (www_path != NULL) {
buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd,
www_path);
if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0)
goto end;
while ((i = SSL_read(scon, buf, sizeof(buf))) > 0)
bytes_read += i;
}
SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
if ((fd = SSL_get_fd(scon)) >= 0)
BIO_closesocket(fd);
nConn += 1;
if (SSL_session_reused(scon)) {
ver = 'r';
} else {
ver = SSL_version(scon);
if (ver == TLS1_VERSION)
ver = 't';
else if (ver == SSL3_VERSION)
ver = '3';
else
ver = '*';
}
fputc(ver, stdout);
fflush(stdout);
}
totalTime += tm_Time_F(STOP); /* Add the time for this iteration */
printf
("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n",
nConn, totalTime, ((double)nConn / totalTime), bytes_read);
if (nConn > 0)
printf
("%d connections in %ld real seconds, %ld bytes read per connection\n",
nConn, (long)time(NULL) - finishtime + maxtime, bytes_read / nConn);
else
printf("0 connections in %ld real seconds\n",
(long)time(NULL) - finishtime + maxtime);
ret = 0;
end:
SSL_free(scon);
SSL_CTX_free(ctx);
return ret;
}
/*-
* doConnection - make a connection
*/
static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx)
{
BIO *conn;
SSL *serverCon;
int i;
if ((conn = BIO_new(BIO_s_connect())) == NULL)
return NULL;
if (BIO_set_conn_hostname(conn, host) <= 0
|| BIO_set_conn_mode(conn, BIO_SOCK_NODELAY) <= 0) {
BIO_free(conn);
return NULL;
}
if (scon == NULL) {
serverCon = SSL_new(ctx);
if (serverCon == NULL) {
BIO_free(conn);
return NULL;
}
} else {
serverCon = scon;
SSL_set_connect_state(serverCon);
}
SSL_set_bio(serverCon, conn, conn);
/* ok, lets connect */
i = SSL_connect(serverCon);
if (i <= 0) {
BIO_printf(bio_err, "ERROR\n");
if (verify_args.error != X509_V_OK)
BIO_printf(bio_err, "verify error:%s\n",
X509_verify_cert_error_string(verify_args.error));
else
ERR_print_errors(bio_err);
if (scon == NULL)
SSL_free(serverCon);
return NULL;
}
#if defined(SOL_SOCKET) && defined(SO_LINGER)
{
struct linger no_linger;
int fd;
no_linger.l_onoff = 1;
no_linger.l_linger = 0;
fd = SSL_get_fd(serverCon);
if (fd >= 0)
(void)setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&no_linger,
sizeof(no_linger));
}
#endif
return serverCon;
}
#endif /* OPENSSL_NO_SOCK */
| 14,204 | 29.031712 | 86 |
c
|
openssl
|
openssl-master/apps/sess_id.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT,
OPT_TEXT, OPT_CERT, OPT_NOOUT, OPT_CONTEXT
} OPTION_CHOICE;
const OPTIONS sess_id_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"context", OPT_CONTEXT, 's', "Set the session ID context"},
OPT_SECTION("Input"),
{"in", OPT_IN, 's', "Input file - default stdin"},
{"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file - default stdout"},
{"outform", OPT_OUTFORM, 'f',
"Output format - default PEM (PEM, DER or NSS)"},
{"text", OPT_TEXT, '-', "Print ssl session id details"},
{"cert", OPT_CERT, '-', "Output certificate "},
{"noout", OPT_NOOUT, '-', "Don't output the encoded session info"},
{NULL}
};
static SSL_SESSION *load_sess_id(char *file, int format);
int sess_id_main(int argc, char **argv)
{
SSL_SESSION *x = NULL;
X509 *peer = NULL;
BIO *out = NULL;
char *infile = NULL, *outfile = NULL, *context = NULL, *prog;
int informat = FORMAT_PEM, outformat = FORMAT_PEM;
int cert = 0, noout = 0, text = 0, ret = 1, i, num = 0;
OPTION_CHOICE o;
prog = opt_init(argc, argv, sess_id_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(sess_id_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER | OPT_FMT_NSS,
&outformat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_TEXT:
text = ++num;
break;
case OPT_CERT:
cert = ++num;
break;
case OPT_NOOUT:
noout = ++num;
break;
case OPT_CONTEXT:
context = opt_arg();
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
x = load_sess_id(infile, informat);
if (x == NULL) {
goto end;
}
peer = SSL_SESSION_get0_peer(x);
if (context != NULL) {
size_t ctx_len = strlen(context);
if (ctx_len > SSL_MAX_SID_CTX_LENGTH) {
BIO_printf(bio_err, "Context too long\n");
goto end;
}
if (!SSL_SESSION_set1_id_context(x, (unsigned char *)context,
ctx_len)) {
BIO_printf(bio_err, "Error setting id context\n");
goto end;
}
}
if (!noout || text) {
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
}
if (text) {
SSL_SESSION_print(out, x);
if (cert) {
if (peer == NULL)
BIO_puts(out, "No certificate present\n");
else
X509_print(out, peer);
}
}
if (!noout && !cert) {
if (outformat == FORMAT_ASN1) {
i = i2d_SSL_SESSION_bio(out, x);
} else if (outformat == FORMAT_PEM) {
i = PEM_write_bio_SSL_SESSION(out, x);
} else if (outformat == FORMAT_NSS) {
i = SSL_SESSION_print_keylog(out, x);
} else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
if (!i) {
BIO_printf(bio_err, "unable to write SSL_SESSION\n");
goto end;
}
} else if (!noout && (peer != NULL)) { /* just print the certificate */
if (outformat == FORMAT_ASN1) {
i = (int)i2d_X509_bio(out, peer);
} else if (outformat == FORMAT_PEM) {
i = PEM_write_bio_X509(out, peer);
} else {
BIO_printf(bio_err, "bad output format specified for outfile\n");
goto end;
}
if (!i) {
BIO_printf(bio_err, "unable to write X509\n");
goto end;
}
}
ret = 0;
end:
BIO_free_all(out);
SSL_SESSION_free(x);
return ret;
}
static SSL_SESSION *load_sess_id(char *infile, int format)
{
SSL_SESSION *x = NULL;
BIO *in = NULL;
in = bio_open_default(infile, 'r', format);
if (in == NULL)
goto end;
if (format == FORMAT_ASN1)
x = d2i_SSL_SESSION_bio(in, NULL);
else
x = PEM_read_bio_SSL_SESSION(in, NULL, NULL, NULL);
if (x == NULL) {
BIO_printf(bio_err, "unable to load SSL_SESSION\n");
ERR_print_errors(bio_err);
goto end;
}
end:
BIO_free(in);
return x;
}
| 5,607 | 27.323232 | 77 |
c
|
openssl
|
openssl-master/apps/smime.c
|
/*
* Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* S/MIME utility function */
#include <stdio.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/crypto.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/x509_vfy.h>
#include <openssl/x509v3.h>
static int save_certs(char *signerfile, STACK_OF(X509) *signers);
static int smime_cb(int ok, X509_STORE_CTX *ctx);
#define SMIME_OP 0x10
#define SMIME_IP 0x20
#define SMIME_SIGNERS 0x40
#define SMIME_ENCRYPT (1 | SMIME_OP)
#define SMIME_DECRYPT (2 | SMIME_IP)
#define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
#define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
#define SMIME_VERIFY (4 | SMIME_IP)
#define SMIME_PK7OUT (5 | SMIME_IP | SMIME_OP)
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_RESIGN, OPT_VERIFY,
OPT_PK7OUT, OPT_TEXT, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCHAIN,
OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP,
OPT_BINARY, OPT_NOSIGS, OPT_STREAM, OPT_INDEF, OPT_NOINDEF,
OPT_CRLFEOL, OPT_ENGINE, OPT_PASSIN,
OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_MD,
OPT_CIPHER, OPT_INKEY, OPT_KEYFORM, OPT_CERTFILE, OPT_CAFILE,
OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE, OPT_NOCAPATH, OPT_NOCASTORE,
OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG,
OPT_V_ENUM,
OPT_IN, OPT_INFORM, OPT_OUT,
OPT_OUTFORM, OPT_CONTENT
} OPTION_CHOICE;
const OPTIONS smime_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"in", OPT_IN, '<', "Input file"},
{"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
{"out", OPT_OUT, '>', "Output file"},
{"outform", OPT_OUTFORM, 'c',
"Output format SMIME (default), PEM or DER"},
{"inkey", OPT_INKEY, 's',
"Input private key (if not signer or recipient)"},
{"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"stream", OPT_STREAM, '-', "Enable CMS streaming" },
{"indef", OPT_INDEF, '-', "Same as -stream" },
{"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
OPT_CONFIG_OPTION,
OPT_SECTION("Action"),
{"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
{"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
{"sign", OPT_SIGN, '-', "Sign message"},
{"resign", OPT_RESIGN, '-', "Resign a signed message"},
{"verify", OPT_VERIFY, '-', "Verify signed message"},
{"pk7out", OPT_PK7OUT, '-', "Output PKCS#7 structure"},
OPT_SECTION("Signing/Encryption"),
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
{"", OPT_CIPHER, '-', "Any supported cipher"},
{"nointern", OPT_NOINTERN, '-',
"Don't search certificates in message for signer"},
{"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
{"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
{"binary", OPT_BINARY, '-', "Don't translate message to text"},
{"signer", OPT_SIGNER, 's', "Signer certificate file"},
{"content", OPT_CONTENT, '<',
"Supply or override content for detached signature"},
{"nocerts", OPT_NOCERTS, '-',
"Don't include signers certificate when signing"},
OPT_SECTION("Verification/Decryption"),
{"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
{"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
{"certfile", OPT_CERTFILE, '<', "Other certificates file"},
{"recip", OPT_RECIP, '<', "Recipient certificate file for decryption"},
OPT_SECTION("Email"),
{"to", OPT_TO, 's', "To address"},
{"from", OPT_FROM, 's', "From address"},
{"subject", OPT_SUBJECT, 's', "Subject"},
{"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
{"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
OPT_SECTION("Certificate chain"),
{"CApath", OPT_CAPATH, '/', "Trusted certificates directory"},
{"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
{"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
{"no-CAfile", OPT_NOCAFILE, '-',
"Do not load the default certificates file"},
{"no-CApath", OPT_NOCAPATH, '-',
"Do not load certificates from the default certificates directory"},
{"no-CAstore", OPT_NOCASTORE, '-',
"Do not load certificates from the default certificates store"},
{"nochain", OPT_NOCHAIN, '-',
"set PKCS7_NOCHAIN so certificates contained in the message are not used as untrusted CAs" },
{"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only"},
OPT_R_OPTIONS,
OPT_V_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"cert", 0, 0, "Recipient certs, used when encrypting"},
{NULL}
};
static const char *operation_name(int operation)
{
switch (operation) {
case SMIME_ENCRYPT:
return "encrypt";
case SMIME_DECRYPT:
return "decrypt";
case SMIME_SIGN:
return "sign";
case SMIME_RESIGN:
return "resign";
case SMIME_VERIFY:
return "verify";
case SMIME_PK7OUT:
return "pk7out";
default:
return "(invalid operation)";
}
}
#define SET_OPERATION(op) \
((operation != 0 && (operation != (op))) \
? 0 * BIO_printf(bio_err, "%s: Cannot use -%s together with -%s\n", \
prog, operation_name(op), operation_name(operation)) \
: (operation = (op)))
int smime_main(int argc, char **argv)
{
CONF *conf = NULL;
BIO *in = NULL, *out = NULL, *indata = NULL;
EVP_PKEY *key = NULL;
PKCS7 *p7 = NULL;
STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
STACK_OF(X509) *encerts = NULL, *other = NULL;
X509 *cert = NULL, *recip = NULL, *signer = NULL;
X509_STORE *store = NULL;
X509_VERIFY_PARAM *vpm = NULL;
EVP_CIPHER *cipher = NULL;
EVP_MD *sign_md = NULL;
const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog = NULL;
char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = NULL;
char *passinarg = NULL, *passin = NULL, *to = NULL, *from = NULL;
char *subject = NULL, *digestname = NULL, *ciphername = NULL;
OPTION_CHOICE o;
int noCApath = 0, noCAfile = 0, noCAstore = 0;
int flags = PKCS7_DETACHED, operation = 0, ret = 0, indef = 0;
int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform =
FORMAT_UNDEF;
int vpmtouched = 0, rv = 0;
ENGINE *e = NULL;
const char *mime_eol = "\n";
OSSL_LIB_CTX *libctx = app_get0_libctx();
if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
return 1;
opt_set_unknown_name("cipher");
prog = opt_init(argc, argv, smime_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(smime_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENCRYPT:
if (!SET_OPERATION(SMIME_ENCRYPT))
goto end;
break;
case OPT_DECRYPT:
if (!SET_OPERATION(SMIME_DECRYPT))
goto end;
break;
case OPT_SIGN:
if (!SET_OPERATION(SMIME_SIGN))
goto end;
break;
case OPT_RESIGN:
if (!SET_OPERATION(SMIME_RESIGN))
goto end;
break;
case OPT_VERIFY:
if (!SET_OPERATION(SMIME_VERIFY))
goto end;
break;
case OPT_PK7OUT:
if (!SET_OPERATION(SMIME_PK7OUT))
goto end;
break;
case OPT_TEXT:
flags |= PKCS7_TEXT;
break;
case OPT_NOINTERN:
flags |= PKCS7_NOINTERN;
break;
case OPT_NOVERIFY:
flags |= PKCS7_NOVERIFY;
break;
case OPT_NOCHAIN:
flags |= PKCS7_NOCHAIN;
break;
case OPT_NOCERTS:
flags |= PKCS7_NOCERTS;
break;
case OPT_NOATTR:
flags |= PKCS7_NOATTR;
break;
case OPT_NODETACH:
flags &= ~PKCS7_DETACHED;
break;
case OPT_NOSMIMECAP:
flags |= PKCS7_NOSMIMECAP;
break;
case OPT_BINARY:
flags |= PKCS7_BINARY;
break;
case OPT_NOSIGS:
flags |= PKCS7_NOSIGS;
break;
case OPT_STREAM:
case OPT_INDEF:
indef = 1;
break;
case OPT_NOINDEF:
indef = 0;
break;
case OPT_CRLFEOL:
flags |= PKCS7_CRLFEOL;
mime_eol = "\r\n";
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_CONFIG:
conf = app_load_config_modules(opt_arg());
if (conf == NULL)
goto end;
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_TO:
to = opt_arg();
break;
case OPT_FROM:
from = opt_arg();
break;
case OPT_SUBJECT:
subject = opt_arg();
break;
case OPT_SIGNER:
/* If previous -signer argument add signer to list */
if (signerfile != NULL) {
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (keyfile == NULL)
keyfile = signerfile;
if (skkeys == NULL
&& (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(skkeys, keyfile);
keyfile = NULL;
}
signerfile = opt_arg();
break;
case OPT_RECIP:
recipfile = opt_arg();
break;
case OPT_MD:
digestname = opt_arg();
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_INKEY:
/* If previous -inkey argument add signer to list */
if (keyfile != NULL) {
if (signerfile == NULL) {
BIO_printf(bio_err,
"%s: Must have -signer before -inkey\n", prog);
goto opthelp;
}
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
signerfile = NULL;
if (skkeys == NULL
&& (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
keyfile = opt_arg();
break;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
goto opthelp;
break;
case OPT_CERTFILE:
certfile = opt_arg();
break;
case OPT_CAFILE:
CAfile = opt_arg();
break;
case OPT_CAPATH:
CApath = opt_arg();
break;
case OPT_CASTORE:
CAstore = opt_arg();
break;
case OPT_NOCAFILE:
noCAfile = 1;
break;
case OPT_NOCAPATH:
noCApath = 1;
break;
case OPT_NOCASTORE:
noCAstore = 1;
break;
case OPT_CONTENT:
contfile = opt_arg();
break;
case OPT_V_CASES:
if (!opt_verify(o, vpm))
goto opthelp;
vpmtouched++;
break;
}
}
/* Extra arguments are files with recipient keys. */
argc = opt_num_rest();
argv = opt_rest();
if (!app_RAND_load())
goto end;
if (digestname != NULL) {
if (!opt_md(digestname, &sign_md))
goto opthelp;
}
if (!opt_cipher_any(ciphername, &cipher))
goto opthelp;
if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
goto opthelp;
}
if (!operation) {
BIO_puts(bio_err,
"No operation (-encrypt|-sign|...) specified\n");
goto opthelp;
}
if (operation & SMIME_SIGNERS) {
/* Check to see if any final signer needs to be appended */
if (keyfile && !signerfile) {
BIO_puts(bio_err, "Illegal -inkey without -signer\n");
goto opthelp;
}
if (signerfile != NULL) {
if (sksigners == NULL
&& (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
sk_OPENSSL_STRING_push(sksigners, signerfile);
if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
goto end;
if (!keyfile)
keyfile = signerfile;
sk_OPENSSL_STRING_push(skkeys, keyfile);
}
if (sksigners == NULL) {
BIO_printf(bio_err, "No signer certificate specified\n");
goto opthelp;
}
signerfile = NULL;
keyfile = NULL;
} else if (operation == SMIME_DECRYPT) {
if (recipfile == NULL && keyfile == NULL) {
BIO_printf(bio_err,
"No recipient certificate or key specified\n");
goto opthelp;
}
} else if (operation == SMIME_ENCRYPT) {
if (argc == 0) {
BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
goto opthelp;
}
}
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
ret = 2;
if (!(operation & SMIME_SIGNERS))
flags &= ~PKCS7_DETACHED;
if (!(operation & SMIME_OP)) {
if (flags & PKCS7_BINARY)
outformat = FORMAT_BINARY;
}
if (!(operation & SMIME_IP)) {
if (flags & PKCS7_BINARY)
informat = FORMAT_BINARY;
}
if (operation == SMIME_ENCRYPT) {
if (cipher == NULL) {
#ifndef OPENSSL_NO_DES
cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
#else
BIO_printf(bio_err, "No cipher selected\n");
goto end;
#endif
}
encerts = sk_X509_new_null();
if (encerts == NULL)
goto end;
while (*argv != NULL) {
cert = load_cert(*argv, FORMAT_UNDEF,
"recipient certificate file");
if (cert == NULL)
goto end;
sk_X509_push(encerts, cert);
cert = NULL;
argv++;
}
}
if (certfile != NULL) {
if (!load_certs(certfile, 0, &other, NULL, "certificates")) {
ERR_print_errors(bio_err);
goto end;
}
}
if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
if ((recip = load_cert(recipfile, FORMAT_UNDEF,
"recipient certificate file")) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
}
if (operation == SMIME_DECRYPT) {
if (keyfile == NULL)
keyfile = recipfile;
} else if (operation == SMIME_SIGN) {
if (keyfile == NULL)
keyfile = signerfile;
} else {
keyfile = NULL;
}
if (keyfile != NULL) {
key = load_key(keyfile, keyform, 0, passin, e, "signing key");
if (key == NULL)
goto end;
}
in = bio_open_default(infile, 'r', informat);
if (in == NULL)
goto end;
if (operation & SMIME_IP) {
PKCS7 *p7_in = NULL;
p7 = PKCS7_new_ex(libctx, app_get0_propq());
if (p7 == NULL) {
BIO_printf(bio_err, "Error allocating PKCS7 object\n");
goto end;
}
if (informat == FORMAT_SMIME) {
p7_in = SMIME_read_PKCS7_ex(in, &indata, &p7);
} else if (informat == FORMAT_PEM) {
p7_in = PEM_read_bio_PKCS7(in, &p7, NULL, NULL);
} else if (informat == FORMAT_ASN1) {
p7_in = d2i_PKCS7_bio(in, &p7);
} else {
BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
goto end;
}
if (p7_in == NULL) {
BIO_printf(bio_err, "Error reading S/MIME message\n");
goto end;
}
if (contfile != NULL) {
BIO_free(indata);
if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
BIO_printf(bio_err, "Can't read content file %s\n", contfile);
goto end;
}
}
}
out = bio_open_default(outfile, 'w', outformat);
if (out == NULL)
goto end;
if (operation == SMIME_VERIFY) {
if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore)) == NULL)
goto end;
X509_STORE_set_verify_cb(store, smime_cb);
if (vpmtouched)
X509_STORE_set1_param(store, vpm);
}
ret = 3;
if (operation == SMIME_ENCRYPT) {
if (indef)
flags |= PKCS7_STREAM;
p7 = PKCS7_encrypt_ex(encerts, in, cipher, flags, libctx, app_get0_propq());
} else if (operation & SMIME_SIGNERS) {
int i;
/*
* If detached data content we only enable streaming if S/MIME output
* format.
*/
if (operation == SMIME_SIGN) {
if (flags & PKCS7_DETACHED) {
if (outformat == FORMAT_SMIME)
flags |= PKCS7_STREAM;
} else if (indef) {
flags |= PKCS7_STREAM;
}
flags |= PKCS7_PARTIAL;
p7 = PKCS7_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq());
if (p7 == NULL)
goto end;
if (flags & PKCS7_NOCERTS) {
for (i = 0; i < sk_X509_num(other); i++) {
X509 *x = sk_X509_value(other, i);
PKCS7_add_certificate(p7, x);
}
}
} else {
flags |= PKCS7_REUSE_DIGEST;
}
for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
signerfile = sk_OPENSSL_STRING_value(sksigners, i);
keyfile = sk_OPENSSL_STRING_value(skkeys, i);
signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate");
if (signer == NULL)
goto end;
key = load_key(keyfile, keyform, 0, passin, e, "signing key");
if (key == NULL)
goto end;
if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags))
goto end;
X509_free(signer);
signer = NULL;
EVP_PKEY_free(key);
key = NULL;
}
/* If not streaming or resigning finalize structure */
if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) {
if (!PKCS7_final(p7, in, flags))
goto end;
}
}
if (p7 == NULL) {
BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
goto end;
}
ret = 4;
if (operation == SMIME_DECRYPT) {
if (!PKCS7_decrypt(p7, key, recip, out, flags)) {
BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
goto end;
}
} else if (operation == SMIME_VERIFY) {
STACK_OF(X509) *signers;
if (PKCS7_verify(p7, other, store, indata, out, flags))
BIO_printf(bio_err, "Verification successful\n");
else {
BIO_printf(bio_err, "Verification failure\n");
goto end;
}
signers = PKCS7_get0_signers(p7, other, flags);
if (!save_certs(signerfile, signers)) {
BIO_printf(bio_err, "Error writing signers to %s\n", signerfile);
ret = 5;
goto end;
}
sk_X509_free(signers);
} else if (operation == SMIME_PK7OUT) {
PEM_write_bio_PKCS7(out, p7);
} else {
if (to)
BIO_printf(out, "To: %s%s", to, mime_eol);
if (from)
BIO_printf(out, "From: %s%s", from, mime_eol);
if (subject)
BIO_printf(out, "Subject: %s%s", subject, mime_eol);
if (outformat == FORMAT_SMIME) {
if (operation == SMIME_RESIGN)
rv = SMIME_write_PKCS7(out, p7, indata, flags);
else
rv = SMIME_write_PKCS7(out, p7, in, flags);
} else if (outformat == FORMAT_PEM) {
rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags);
} else if (outformat == FORMAT_ASN1) {
rv = i2d_PKCS7_bio_stream(out, p7, in, flags);
} else {
BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
goto end;
}
if (rv == 0) {
BIO_printf(bio_err, "Error writing output\n");
ret = 3;
goto end;
}
}
ret = 0;
end:
if (ret)
ERR_print_errors(bio_err);
OSSL_STACK_OF_X509_free(encerts);
OSSL_STACK_OF_X509_free(other);
X509_VERIFY_PARAM_free(vpm);
sk_OPENSSL_STRING_free(sksigners);
sk_OPENSSL_STRING_free(skkeys);
X509_STORE_free(store);
X509_free(cert);
X509_free(recip);
X509_free(signer);
EVP_PKEY_free(key);
EVP_MD_free(sign_md);
EVP_CIPHER_free(cipher);
PKCS7_free(p7);
release_engine(e);
BIO_free(in);
BIO_free(indata);
BIO_free_all(out);
OPENSSL_free(passin);
NCONF_free(conf);
return ret;
}
static int save_certs(char *signerfile, STACK_OF(X509) *signers)
{
int i;
BIO *tmp;
if (signerfile == NULL)
return 1;
tmp = BIO_new_file(signerfile, "w");
if (tmp == NULL)
return 0;
for (i = 0; i < sk_X509_num(signers); i++)
PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
BIO_free(tmp);
return 1;
}
/* Minimal callback just to output policy info (if any) */
static int smime_cb(int ok, X509_STORE_CTX *ctx)
{
int error;
error = X509_STORE_CTX_get_error(ctx);
if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
&& ((error != X509_V_OK) || (ok != 2)))
return ok;
policies_print(ctx);
return ok;
}
| 23,994 | 31.381916 | 98 |
c
|
openssl
|
openssl-master/apps/spkac.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_NOOUT, OPT_PUBKEY, OPT_VERIFY, OPT_IN, OPT_OUT,
OPT_ENGINE, OPT_KEY, OPT_CHALLENGE, OPT_PASSIN, OPT_SPKAC,
OPT_SPKSECT, OPT_KEYFORM, OPT_DIGEST,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS spkac_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"spksect", OPT_SPKSECT, 's',
"Specify the name of an SPKAC-dedicated section of configuration"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
{"in", OPT_IN, '<', "Input file"},
{"key", OPT_KEY, '<', "Create SPKAC using private key"},
{"keyform", OPT_KEYFORM, 'f', "Private key file format (ENGINE, other values ignored)"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"challenge", OPT_CHALLENGE, 's', "Challenge string"},
{"spkac", OPT_SPKAC, 's', "Alternative SPKAC name"},
OPT_SECTION("Output"),
{"digest", OPT_DIGEST, 's', "Sign new SPKAC with the specified digest (default: MD5)" },
{"out", OPT_OUT, '>', "Output file"},
{"noout", OPT_NOOUT, '-', "Don't print SPKAC"},
{"pubkey", OPT_PUBKEY, '-', "Output public key"},
{"verify", OPT_VERIFY, '-', "Verify SPKAC signature"},
OPT_PROV_OPTIONS,
{NULL}
};
int spkac_main(int argc, char **argv)
{
BIO *out = NULL;
CONF *conf = NULL;
ENGINE *e = NULL;
EVP_PKEY *pkey = NULL;
NETSCAPE_SPKI *spki = NULL;
char *challenge = NULL, *keyfile = NULL;
char *infile = NULL, *outfile = NULL, *passinarg = NULL, *passin = NULL;
char *spkstr = NULL, *prog;
const char *spkac = "SPKAC", *spksect = "default";
const char *digest = "MD5";
EVP_MD *md = NULL;
int i, ret = 1, verify = 0, noout = 0, pubkey = 0;
int keyformat = FORMAT_UNDEF;
OPTION_CHOICE o;
prog = opt_init(argc, argv, spkac_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(spkac_options);
ret = 0;
goto end;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_PUBKEY:
pubkey = 1;
break;
case OPT_VERIFY:
verify = 1;
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_KEY:
keyfile = opt_arg();
break;
case OPT_KEYFORM:
if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
goto opthelp;
break;
case OPT_CHALLENGE:
challenge = opt_arg();
break;
case OPT_SPKAC:
spkac = opt_arg();
break;
case OPT_SPKSECT:
spksect = opt_arg();
break;
case OPT_DIGEST:
digest = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
if (keyfile != NULL) {
if (!opt_md(digest, &md))
goto end;
pkey = load_key(strcmp(keyfile, "-") ? keyfile : NULL,
keyformat, 1, passin, e, "private key");
if (pkey == NULL)
goto end;
spki = NETSCAPE_SPKI_new();
if (spki == NULL)
goto end;
if (challenge != NULL)
ASN1_STRING_set(spki->spkac->challenge,
challenge, (int)strlen(challenge));
if (!NETSCAPE_SPKI_set_pubkey(spki, pkey)) {
BIO_printf(bio_err, "Error setting public key\n");
goto end;
}
i = NETSCAPE_SPKI_sign(spki, pkey, md);
if (i <= 0) {
BIO_printf(bio_err, "Error signing SPKAC\n");
goto end;
}
spkstr = NETSCAPE_SPKI_b64_encode(spki);
if (spkstr == NULL)
goto end;
out = bio_open_default(outfile, 'w', FORMAT_TEXT);
if (out == NULL) {
OPENSSL_free(spkstr);
goto end;
}
BIO_printf(out, "SPKAC=%s\n", spkstr);
OPENSSL_free(spkstr);
ret = 0;
goto end;
}
if ((conf = app_load_config(infile)) == NULL)
goto end;
spkstr = NCONF_get_string(conf, spksect, spkac);
if (spkstr == NULL) {
BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n", spkac);
ERR_print_errors(bio_err);
goto end;
}
spki = NETSCAPE_SPKI_b64_decode(spkstr, -1);
if (spki == NULL) {
BIO_printf(bio_err, "Error loading SPKAC\n");
ERR_print_errors(bio_err);
goto end;
}
out = bio_open_default(outfile, 'w', FORMAT_TEXT);
if (out == NULL)
goto end;
if (!noout)
NETSCAPE_SPKI_print(out, spki);
pkey = NETSCAPE_SPKI_get_pubkey(spki);
if (verify) {
i = NETSCAPE_SPKI_verify(spki, pkey);
if (i > 0) {
BIO_printf(bio_err, "Signature OK\n");
} else {
BIO_printf(bio_err, "Signature Failure\n");
ERR_print_errors(bio_err);
goto end;
}
}
if (pubkey)
PEM_write_bio_PUBKEY(out, pkey);
ret = 0;
end:
EVP_MD_free(md);
NCONF_free(conf);
NETSCAPE_SPKI_free(spki);
BIO_free_all(out);
EVP_PKEY_free(pkey);
release_engine(e);
OPENSSL_free(passin);
return ret;
}
| 6,619 | 27.412017 | 92 |
c
|
openssl
|
openssl-master/apps/srp.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2004, EdelKey Project. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*
* Originally written by Christophe Renou and Peter Sylvester,
* for the EdelKey project.
*/
/* SRP is deprecated, so we're going to have to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/conf.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/txt_db.h>
#include <openssl/buffer.h>
#include <openssl/srp.h>
#include "apps.h"
#include "progs.h"
#define BASE_SECTION "srp"
#define CONFIG_FILE "openssl.cnf"
#define ENV_DATABASE "srpvfile"
#define ENV_DEFAULT_SRP "default_srp"
static int get_index(CA_DB *db, char *id, char type)
{
char **pp;
int i;
if (id == NULL)
return -1;
if (type == DB_SRP_INDEX) {
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] == DB_SRP_INDEX
&& strcmp(id, pp[DB_srpid]) == 0)
return i;
}
} else {
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] != DB_SRP_INDEX
&& strcmp(id, pp[DB_srpid]) == 0)
return i;
}
}
return -1;
}
static void print_entry(CA_DB *db, int indx, int verbose, char *s)
{
if (indx >= 0 && verbose) {
int j;
char **pp = sk_OPENSSL_PSTRING_value(db->db->data, indx);
BIO_printf(bio_err, "%s \"%s\"\n", s, pp[DB_srpid]);
for (j = 0; j < DB_NUMBER; j++) {
BIO_printf(bio_err, " %d = \"%s\"\n", j, pp[j]);
}
}
}
static void print_index(CA_DB *db, int indexindex, int verbose)
{
print_entry(db, indexindex, verbose, "g N entry");
}
static void print_user(CA_DB *db, int userindex, int verbose)
{
if (verbose > 0) {
char **pp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
if (pp[DB_srptype][0] != 'I') {
print_entry(db, userindex, verbose, "User entry");
print_entry(db, get_index(db, pp[DB_srpgN], 'I'), verbose,
"g N entry");
}
}
}
static int update_index(CA_DB *db, char **row)
{
char **irow;
int i;
irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row pointers");
for (i = 0; i < DB_NUMBER; i++)
irow[i] = row[i];
irow[DB_NUMBER] = NULL;
if (!TXT_DB_insert(db->db, irow)) {
BIO_printf(bio_err, "failed to update srpvfile\n");
BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
OPENSSL_free(irow);
return 0;
}
return 1;
}
static char *lookup_conf(const CONF *conf, const char *section, const char *tag)
{
char *entry = NCONF_get_string(conf, section, tag);
if (entry == NULL)
BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag);
return entry;
}
static char *srp_verify_user(const char *user, const char *srp_verifier,
char *srp_usersalt, const char *g, const char *N,
const char *passin, int verbose)
{
char password[1025];
PW_CB_DATA cb_tmp;
char *verifier = NULL;
char *gNid = NULL;
int len;
cb_tmp.prompt_info = user;
cb_tmp.password = passin;
len = password_callback(password, sizeof(password)-1, 0, &cb_tmp);
if (len > 0) {
password[len] = 0;
if (verbose)
BIO_printf(bio_err,
"Validating\n user=\"%s\"\n srp_verifier=\"%s\"\n srp_usersalt=\"%s\"\n g=\"%s\"\n N=\"%s\"\n",
user, srp_verifier, srp_usersalt, g, N);
if (verbose > 1)
BIO_printf(bio_err, "Pass %s\n", password);
OPENSSL_assert(srp_usersalt != NULL);
if ((gNid = SRP_create_verifier(user, password, &srp_usersalt,
&verifier, N, g)) == NULL) {
BIO_printf(bio_err, "Internal error validating SRP verifier\n");
} else {
if (strcmp(verifier, srp_verifier))
gNid = NULL;
OPENSSL_free(verifier);
}
OPENSSL_cleanse(password, len);
}
return gNid;
}
static char *srp_create_user(char *user, char **srp_verifier,
char **srp_usersalt, char *g, char *N,
char *passout, int verbose)
{
char password[1025];
PW_CB_DATA cb_tmp;
char *gNid = NULL;
char *salt = NULL;
int len;
cb_tmp.prompt_info = user;
cb_tmp.password = passout;
len = password_callback(password, sizeof(password)-1, 1, &cb_tmp);
if (len > 0) {
password[len] = 0;
if (verbose)
BIO_printf(bio_err, "Creating\n user=\"%s\"\n g=\"%s\"\n N=\"%s\"\n",
user, g, N);
if ((gNid = SRP_create_verifier(user, password, &salt,
srp_verifier, N, g)) == NULL) {
BIO_printf(bio_err, "Internal error creating SRP verifier\n");
} else {
*srp_usersalt = salt;
}
OPENSSL_cleanse(password, len);
if (verbose > 1)
BIO_printf(bio_err, "gNid=%s salt =\"%s\"\n verifier =\"%s\"\n",
gNid, salt, *srp_verifier);
}
return gNid;
}
typedef enum OPTION_choice {
OPT_COMMON,
OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SRPVFILE, OPT_ADD,
OPT_DELETE, OPT_MODIFY, OPT_LIST, OPT_GN, OPT_USERINFO,
OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS srp_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [user...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"verbose", OPT_VERBOSE, '-', "Talk a lot while doing things"},
{"config", OPT_CONFIG, '<', "A config file"},
{"name", OPT_NAME, 's', "The particular srp definition to use"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Action"),
{"add", OPT_ADD, '-', "Add a user and SRP verifier"},
{"modify", OPT_MODIFY, '-', "Modify the SRP verifier of an existing user"},
{"delete", OPT_DELETE, '-', "Delete user from verifier file"},
{"list", OPT_LIST, '-', "List users"},
OPT_SECTION("Configuration"),
{"srpvfile", OPT_SRPVFILE, '<', "The srp verifier file name"},
{"gn", OPT_GN, 's', "Set g and N values to be used for new verifier"},
{"userinfo", OPT_USERINFO, 's', "Additional info to be set for user"},
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"user", 0, 0, "Username(s) to process (optional)"},
{NULL}
};
int srp_main(int argc, char **argv)
{
ENGINE *e = NULL;
CA_DB *db = NULL;
CONF *conf = NULL;
int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i;
int doupdatedb = 0, mode = OPT_ERR;
char *user = NULL, *passinarg = NULL, *passoutarg = NULL;
char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL;
char *section = NULL;
char **gNrow = NULL, *configfile = NULL;
char *srpvfile = NULL, **pp, *prog;
OPTION_CHOICE o;
prog = opt_init(argc, argv, srp_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(srp_options);
ret = 0;
goto end;
case OPT_VERBOSE:
verbose++;
break;
case OPT_CONFIG:
configfile = opt_arg();
break;
case OPT_NAME:
section = opt_arg();
break;
case OPT_SRPVFILE:
srpvfile = opt_arg();
break;
case OPT_ADD:
case OPT_DELETE:
case OPT_MODIFY:
case OPT_LIST:
if (mode != OPT_ERR) {
BIO_printf(bio_err,
"%s: Only one of -add/-delete/-modify/-list\n",
prog);
goto opthelp;
}
mode = o;
break;
case OPT_GN:
gN = opt_arg();
break;
case OPT_USERINFO:
userinfo = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Optional parameters are usernames. */
argc = opt_num_rest();
argv = opt_rest();
if (!app_RAND_load())
goto end;
if (srpvfile != NULL && configfile != NULL) {
BIO_printf(bio_err,
"-srpvfile and -configfile cannot be specified together.\n");
goto end;
}
if (mode == OPT_ERR) {
BIO_printf(bio_err,
"Exactly one of the options -add, -delete, -modify -list must be specified.\n");
goto opthelp;
}
if (mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD) {
if (argc == 0) {
BIO_printf(bio_err, "Need at least one user.\n");
goto opthelp;
}
user = *argv++;
}
if ((passinarg != NULL || passoutarg != NULL) && argc != 1) {
BIO_printf(bio_err,
"-passin, -passout arguments only valid with one user.\n");
goto opthelp;
}
if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
if (srpvfile == NULL) {
if (configfile == NULL)
configfile = default_config_file;
conf = app_load_config_verbose(configfile, verbose);
if (conf == NULL)
goto end;
if (configfile != default_config_file && !app_load_modules(conf))
goto end;
/* Lets get the config section we are using */
if (section == NULL) {
if (verbose)
BIO_printf(bio_err,
"trying to read " ENV_DEFAULT_SRP
" in " BASE_SECTION "\n");
section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP);
if (section == NULL)
goto end;
}
app_RAND_load_conf(conf, BASE_SECTION);
if (verbose)
BIO_printf(bio_err,
"trying to read " ENV_DATABASE " in section \"%s\"\n",
section);
srpvfile = lookup_conf(conf, section, ENV_DATABASE);
if (srpvfile == NULL)
goto end;
}
if (verbose)
BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n",
srpvfile);
db = load_index(srpvfile, NULL);
if (db == NULL) {
BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", srpvfile);
goto end;
}
/* Lets check some fields */
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] == DB_SRP_INDEX) {
maxgN = i;
if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0)
gNindex = i;
print_index(db, i, verbose > 1);
}
}
if (verbose)
BIO_printf(bio_err, "Database initialised\n");
if (gNindex >= 0) {
gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex);
print_entry(db, gNindex, verbose > 1, "Default g and N");
} else if (maxgN > 0 && !SRP_get_default_gN(gN)) {
BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
goto end;
} else {
if (verbose)
BIO_printf(bio_err, "Database has no g N information.\n");
gNrow = NULL;
}
if (verbose > 1)
BIO_printf(bio_err, "Starting user processing\n");
while (mode == OPT_LIST || user != NULL) {
int userindex = -1;
if (user != NULL && verbose > 1)
BIO_printf(bio_err, "Processing user \"%s\"\n", user);
if ((userindex = get_index(db, user, 'U')) >= 0)
print_user(db, userindex, (verbose > 0) || mode == OPT_LIST);
if (mode == OPT_LIST) {
if (user == NULL) {
BIO_printf(bio_err, "List all users\n");
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
print_user(db, i, 1);
} else if (userindex < 0) {
BIO_printf(bio_err,
"user \"%s\" does not exist, ignored. t\n", user);
errors++;
}
} else if (mode == OPT_ADD) {
if (userindex >= 0) {
/* reactivation of a new user */
char **row =
sk_OPENSSL_PSTRING_value(db->db->data, userindex);
BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
row[DB_srptype][0] = 'V';
doupdatedb = 1;
} else {
char *row[DB_NUMBER];
char *gNid;
row[DB_srpverifier] = NULL;
row[DB_srpsalt] = NULL;
row[DB_srpinfo] = NULL;
if (!
(gNid =
srp_create_user(user, &(row[DB_srpverifier]),
&(row[DB_srpsalt]),
gNrow ? gNrow[DB_srpsalt] : gN,
gNrow ? gNrow[DB_srpverifier] : NULL,
passout, verbose))) {
BIO_printf(bio_err,
"Cannot create srp verifier for user \"%s\", operation abandoned .\n",
user);
errors++;
goto end;
}
row[DB_srpid] = OPENSSL_strdup(user);
row[DB_srptype] = OPENSSL_strdup("v");
row[DB_srpgN] = OPENSSL_strdup(gNid);
if ((row[DB_srpid] == NULL)
|| (row[DB_srpgN] == NULL)
|| (row[DB_srptype] == NULL)
|| (row[DB_srpverifier] == NULL)
|| (row[DB_srpsalt] == NULL)
|| (userinfo
&& ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))
|| !update_index(db, row)) {
OPENSSL_free(row[DB_srpid]);
OPENSSL_free(row[DB_srpgN]);
OPENSSL_free(row[DB_srpinfo]);
OPENSSL_free(row[DB_srptype]);
OPENSSL_free(row[DB_srpverifier]);
OPENSSL_free(row[DB_srpsalt]);
goto end;
}
doupdatedb = 1;
}
} else if (mode == OPT_MODIFY) {
if (userindex < 0) {
BIO_printf(bio_err,
"user \"%s\" does not exist, operation ignored.\n",
user);
errors++;
} else {
char **row =
sk_OPENSSL_PSTRING_value(db->db->data, userindex);
char type = row[DB_srptype][0];
if (type == 'v') {
BIO_printf(bio_err,
"user \"%s\" already updated, operation ignored.\n",
user);
errors++;
} else {
char *gNid;
if (row[DB_srptype][0] == 'V') {
int user_gN;
char **irow = NULL;
if (verbose)
BIO_printf(bio_err,
"Verifying password for user \"%s\"\n",
user);
if ((user_gN =
get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
irow =
sk_OPENSSL_PSTRING_value(db->db->data,
userindex);
if (!srp_verify_user
(user, row[DB_srpverifier], row[DB_srpsalt],
irow ? irow[DB_srpsalt] : row[DB_srpgN],
irow ? irow[DB_srpverifier] : NULL, passin,
verbose)) {
BIO_printf(bio_err,
"Invalid password for user \"%s\", operation abandoned.\n",
user);
errors++;
goto end;
}
}
if (verbose)
BIO_printf(bio_err, "Password for user \"%s\" ok.\n",
user);
if (!
(gNid =
srp_create_user(user, &(row[DB_srpverifier]),
&(row[DB_srpsalt]),
gNrow ? gNrow[DB_srpsalt] : NULL,
gNrow ? gNrow[DB_srpverifier] : NULL,
passout, verbose))) {
BIO_printf(bio_err,
"Cannot create srp verifier for user \"%s\", operation abandoned.\n",
user);
errors++;
goto end;
}
row[DB_srptype][0] = 'v';
row[DB_srpgN] = OPENSSL_strdup(gNid);
if (row[DB_srpid] == NULL
|| row[DB_srpgN] == NULL
|| row[DB_srptype] == NULL
|| row[DB_srpverifier] == NULL
|| row[DB_srpsalt] == NULL
|| (userinfo
&& ((row[DB_srpinfo] = OPENSSL_strdup(userinfo))
== NULL)))
goto end;
doupdatedb = 1;
}
}
} else if (mode == OPT_DELETE) {
if (userindex < 0) {
BIO_printf(bio_err,
"user \"%s\" does not exist, operation ignored. t\n",
user);
errors++;
} else {
char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);
xpp[DB_srptype][0] = 'R';
doupdatedb = 1;
}
}
user = *argv++;
if (user == NULL) {
/* no more processing in any mode if no users left */
break;
}
}
if (verbose)
BIO_printf(bio_err, "User procession done.\n");
if (doupdatedb) {
/* Lets check some fields */
for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
if (pp[DB_srptype][0] == 'v') {
pp[DB_srptype][0] = 'V';
print_user(db, i, verbose);
}
}
if (verbose)
BIO_printf(bio_err, "Trying to update srpvfile.\n");
if (!save_index(srpvfile, "new", db))
goto end;
if (verbose)
BIO_printf(bio_err, "Temporary srpvfile created.\n");
if (!rotate_index(srpvfile, "new", "old"))
goto end;
if (verbose)
BIO_printf(bio_err, "srpvfile updated.\n");
}
ret = (errors != 0);
end:
if (errors != 0)
if (verbose)
BIO_printf(bio_err, "User errors %d.\n", errors);
if (verbose)
BIO_printf(bio_err, "SRP terminating with code %d.\n", ret);
OPENSSL_free(passin);
OPENSSL_free(passout);
if (ret)
ERR_print_errors(bio_err);
NCONF_free(conf);
free_index(db);
release_engine(e);
return ret;
}
| 21,131 | 32.436709 | 120 |
c
|
openssl
|
openssl-master/apps/storeutl.c
|
/*
* Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include "apps.h"
#include "progs.h"
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/store.h>
#include <openssl/x509v3.h> /* s2i_ASN1_INTEGER */
static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata,
int expected, int criterion, OSSL_STORE_SEARCH *search,
int text, int noout, int recursive, int indent, BIO *out,
const char *prog, OSSL_LIB_CTX *libctx);
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ENGINE, OPT_OUT, OPT_PASSIN,
OPT_NOOUT, OPT_TEXT, OPT_RECURSIVE,
OPT_SEARCHFOR_CERTS, OPT_SEARCHFOR_KEYS, OPT_SEARCHFOR_CRLS,
OPT_CRITERION_SUBJECT, OPT_CRITERION_ISSUER, OPT_CRITERION_SERIAL,
OPT_CRITERION_FINGERPRINT, OPT_CRITERION_ALIAS,
OPT_MD, OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS storeutl_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] uri\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
{"", OPT_MD, '-', "Any supported digest"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Search"),
{"certs", OPT_SEARCHFOR_CERTS, '-', "Search for certificates only"},
{"keys", OPT_SEARCHFOR_KEYS, '-', "Search for keys only"},
{"crls", OPT_SEARCHFOR_CRLS, '-', "Search for CRLs only"},
{"subject", OPT_CRITERION_SUBJECT, 's', "Search by subject"},
{"issuer", OPT_CRITERION_ISSUER, 's', "Search by issuer and serial, issuer name"},
{"serial", OPT_CRITERION_SERIAL, 's', "Search by issuer and serial, serial number"},
{"fingerprint", OPT_CRITERION_FINGERPRINT, 's', "Search by public key fingerprint, given in hex"},
{"alias", OPT_CRITERION_ALIAS, 's', "Search by alias"},
{"r", OPT_RECURSIVE, '-', "Recurse through names"},
OPT_SECTION("Input"),
{"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output file - default stdout"},
{"text", OPT_TEXT, '-', "Print a text form of the objects"},
{"noout", OPT_NOOUT, '-', "No PEM output, just status"},
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"uri", 0, 0, "URI of the store object"},
{NULL}
};
int storeutl_main(int argc, char *argv[])
{
int ret = 1, noout = 0, text = 0, recursive = 0;
char *outfile = NULL, *passin = NULL, *passinarg = NULL;
BIO *out = NULL;
ENGINE *e = NULL;
OPTION_CHOICE o;
char *prog;
PW_CB_DATA pw_cb_data;
int expected = 0;
int criterion = 0;
X509_NAME *subject = NULL, *issuer = NULL;
ASN1_INTEGER *serial = NULL;
unsigned char *fingerprint = NULL;
size_t fingerprintlen = 0;
char *alias = NULL, *digestname = NULL;
OSSL_STORE_SEARCH *search = NULL;
EVP_MD *digest = NULL;
OSSL_LIB_CTX *libctx = app_get0_libctx();
opt_set_unknown_name("digest");
prog = opt_init(argc, argv, storeutl_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(storeutl_options);
ret = 0;
goto end;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_PASSIN:
passinarg = opt_arg();
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_TEXT:
text = 1;
break;
case OPT_RECURSIVE:
recursive = 1;
break;
case OPT_SEARCHFOR_CERTS:
case OPT_SEARCHFOR_KEYS:
case OPT_SEARCHFOR_CRLS:
if (expected != 0) {
BIO_printf(bio_err, "%s: only one search type can be given.\n",
prog);
goto end;
}
{
static const struct {
enum OPTION_choice choice;
int type;
} map[] = {
{OPT_SEARCHFOR_CERTS, OSSL_STORE_INFO_CERT},
{OPT_SEARCHFOR_KEYS, OSSL_STORE_INFO_PKEY},
{OPT_SEARCHFOR_CRLS, OSSL_STORE_INFO_CRL},
};
size_t i;
for (i = 0; i < OSSL_NELEM(map); i++) {
if (o == map[i].choice) {
expected = map[i].type;
break;
}
}
/*
* If expected wasn't set at this point, it means the map
* isn't synchronised with the possible options leading here.
*/
OPENSSL_assert(expected != 0);
}
break;
case OPT_CRITERION_SUBJECT:
if (criterion != 0) {
BIO_printf(bio_err, "%s: criterion already given.\n",
prog);
goto end;
}
criterion = OSSL_STORE_SEARCH_BY_NAME;
if (subject != NULL) {
BIO_printf(bio_err, "%s: subject already given.\n",
prog);
goto end;
}
subject = parse_name(opt_arg(), MBSTRING_UTF8, 1, "subject");
if (subject == NULL)
goto end;
break;
case OPT_CRITERION_ISSUER:
if (criterion != 0
&& criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) {
BIO_printf(bio_err, "%s: criterion already given.\n",
prog);
goto end;
}
criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL;
if (issuer != NULL) {
BIO_printf(bio_err, "%s: issuer already given.\n",
prog);
goto end;
}
issuer = parse_name(opt_arg(), MBSTRING_UTF8, 1, "issuer");
if (issuer == NULL)
goto end;
break;
case OPT_CRITERION_SERIAL:
if (criterion != 0
&& criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) {
BIO_printf(bio_err, "%s: criterion already given.\n",
prog);
goto end;
}
criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL;
if (serial != NULL) {
BIO_printf(bio_err, "%s: serial number already given.\n",
prog);
goto end;
}
if ((serial = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) {
BIO_printf(bio_err, "%s: can't parse serial number argument.\n",
prog);
goto end;
}
break;
case OPT_CRITERION_FINGERPRINT:
if (criterion != 0
|| (criterion == OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT
&& fingerprint != NULL)) {
BIO_printf(bio_err, "%s: criterion already given.\n",
prog);
goto end;
}
criterion = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT;
if (fingerprint != NULL) {
BIO_printf(bio_err, "%s: fingerprint already given.\n",
prog);
goto end;
}
{
long tmplen = 0;
if ((fingerprint = OPENSSL_hexstr2buf(opt_arg(), &tmplen))
== NULL) {
BIO_printf(bio_err,
"%s: can't parse fingerprint argument.\n",
prog);
goto end;
}
fingerprintlen = (size_t)tmplen;
}
break;
case OPT_CRITERION_ALIAS:
if (criterion != 0) {
BIO_printf(bio_err, "%s: criterion already given.\n",
prog);
goto end;
}
criterion = OSSL_STORE_SEARCH_BY_ALIAS;
if (alias != NULL) {
BIO_printf(bio_err, "%s: alias already given.\n",
prog);
goto end;
}
if ((alias = OPENSSL_strdup(opt_arg())) == NULL) {
BIO_printf(bio_err, "%s: can't parse alias argument.\n",
prog);
goto end;
}
break;
case OPT_ENGINE:
e = setup_engine(opt_arg(), 0);
break;
case OPT_MD:
digestname = opt_unknown();
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* One argument, the URI */
if (!opt_check_rest_arg("URI"))
goto opthelp;
argv = opt_rest();
if (!opt_md(digestname, &digest))
goto opthelp;
if (criterion != 0) {
switch (criterion) {
case OSSL_STORE_SEARCH_BY_NAME:
if ((search = OSSL_STORE_SEARCH_by_name(subject)) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
break;
case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL:
if (issuer == NULL || serial == NULL) {
BIO_printf(bio_err,
"%s: both -issuer and -serial must be given.\n",
prog);
goto end;
}
if ((search = OSSL_STORE_SEARCH_by_issuer_serial(issuer, serial))
== NULL) {
ERR_print_errors(bio_err);
goto end;
}
break;
case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT:
if ((search = OSSL_STORE_SEARCH_by_key_fingerprint(digest,
fingerprint,
fingerprintlen))
== NULL) {
ERR_print_errors(bio_err);
goto end;
}
break;
case OSSL_STORE_SEARCH_BY_ALIAS:
if ((search = OSSL_STORE_SEARCH_by_alias(alias)) == NULL) {
ERR_print_errors(bio_err);
goto end;
}
break;
}
}
if (!app_passwd(passinarg, NULL, &passin, NULL)) {
BIO_printf(bio_err, "Error getting passwords\n");
goto end;
}
pw_cb_data.password = passin;
pw_cb_data.prompt_info = argv[0];
out = bio_open_default(outfile, 'w', FORMAT_TEXT);
if (out == NULL)
goto end;
ret = process(argv[0], get_ui_method(), &pw_cb_data,
expected, criterion, search,
text, noout, recursive, 0, out, prog, libctx);
end:
EVP_MD_free(digest);
OPENSSL_free(fingerprint);
OPENSSL_free(alias);
ASN1_INTEGER_free(serial);
X509_NAME_free(subject);
X509_NAME_free(issuer);
OSSL_STORE_SEARCH_free(search);
BIO_free_all(out);
OPENSSL_free(passin);
release_engine(e);
return ret;
}
static int indent_printf(int indent, BIO *bio, const char *format, ...)
{
va_list args;
int ret;
va_start(args, format);
ret = BIO_printf(bio, "%*s", indent, "") + BIO_vprintf(bio, format, args);
va_end(args);
return ret;
}
static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata,
int expected, int criterion, OSSL_STORE_SEARCH *search,
int text, int noout, int recursive, int indent, BIO *out,
const char *prog, OSSL_LIB_CTX *libctx)
{
OSSL_STORE_CTX *store_ctx = NULL;
int ret = 1, items = 0;
if ((store_ctx = OSSL_STORE_open_ex(uri, libctx, app_get0_propq(), uimeth, uidata,
NULL, NULL, NULL))
== NULL) {
BIO_printf(bio_err, "Couldn't open file or uri %s\n", uri);
ERR_print_errors(bio_err);
return ret;
}
if (expected != 0) {
if (!OSSL_STORE_expect(store_ctx, expected)) {
ERR_print_errors(bio_err);
goto end2;
}
}
if (criterion != 0) {
if (!OSSL_STORE_supports_search(store_ctx, criterion)) {
BIO_printf(bio_err,
"%s: the store scheme doesn't support the given search criteria.\n",
prog);
goto end2;
}
if (!OSSL_STORE_find(store_ctx, search)) {
ERR_print_errors(bio_err);
goto end2;
}
}
/* From here on, we count errors, and we'll return the count at the end */
ret = 0;
for (;;) {
OSSL_STORE_INFO *info = OSSL_STORE_load(store_ctx);
int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
const char *infostr =
info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
if (info == NULL) {
if (OSSL_STORE_error(store_ctx)) {
if (recursive)
ERR_clear_error();
else
ERR_print_errors(bio_err);
if (OSSL_STORE_eof(store_ctx))
break;
ret++;
continue;
}
if (OSSL_STORE_eof(store_ctx))
break;
BIO_printf(bio_err,
"ERROR: OSSL_STORE_load() returned NULL without "
"eof or error indications\n");
BIO_printf(bio_err, " This is an error in the loader\n");
ERR_print_errors(bio_err);
ret++;
break;
}
if (type == OSSL_STORE_INFO_NAME) {
const char *name = OSSL_STORE_INFO_get0_NAME(info);
const char *desc = OSSL_STORE_INFO_get0_NAME_description(info);
indent_printf(indent, bio_out, "%d: %s: %s\n", items, infostr,
name);
if (desc != NULL)
indent_printf(indent, bio_out, "%s\n", desc);
} else {
indent_printf(indent, bio_out, "%d: %s\n", items, infostr);
}
/*
* Unfortunately, PEM_X509_INFO_write_bio() is sorely lacking in
* functionality, so we must figure out how exactly to write things
* ourselves...
*/
switch (type) {
case OSSL_STORE_INFO_NAME:
if (recursive) {
const char *suburi = OSSL_STORE_INFO_get0_NAME(info);
ret += process(suburi, uimeth, uidata,
expected, criterion, search,
text, noout, recursive, indent + 2, out, prog,
libctx);
}
break;
case OSSL_STORE_INFO_PARAMS:
if (text)
EVP_PKEY_print_params(out, OSSL_STORE_INFO_get0_PARAMS(info),
0, NULL);
if (!noout)
PEM_write_bio_Parameters(out,
OSSL_STORE_INFO_get0_PARAMS(info));
break;
case OSSL_STORE_INFO_PUBKEY:
if (text)
EVP_PKEY_print_public(out, OSSL_STORE_INFO_get0_PUBKEY(info),
0, NULL);
if (!noout)
PEM_write_bio_PUBKEY(out, OSSL_STORE_INFO_get0_PUBKEY(info));
break;
case OSSL_STORE_INFO_PKEY:
if (text)
EVP_PKEY_print_private(out, OSSL_STORE_INFO_get0_PKEY(info),
0, NULL);
if (!noout)
PEM_write_bio_PrivateKey(out, OSSL_STORE_INFO_get0_PKEY(info),
NULL, NULL, 0, NULL, NULL);
break;
case OSSL_STORE_INFO_CERT:
if (text)
X509_print(out, OSSL_STORE_INFO_get0_CERT(info));
if (!noout)
PEM_write_bio_X509(out, OSSL_STORE_INFO_get0_CERT(info));
break;
case OSSL_STORE_INFO_CRL:
if (text)
X509_CRL_print(out, OSSL_STORE_INFO_get0_CRL(info));
if (!noout)
PEM_write_bio_X509_CRL(out, OSSL_STORE_INFO_get0_CRL(info));
break;
default:
BIO_printf(bio_err, "!!! Unknown code\n");
ret++;
break;
}
items++;
OSSL_STORE_INFO_free(info);
}
indent_printf(indent, out, "Total found: %d\n", items);
end2:
if (!OSSL_STORE_close(store_ctx)) {
ERR_print_errors(bio_err);
ret++;
}
return ret;
}
| 17,064 | 33.267068 | 102 |
c
|
openssl
|
openssl-master/apps/testdsa.h
|
/*
* Copyright 1998-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/param_build.h>
/* used by speed.c */
EVP_PKEY *get_dsa(int);
static unsigned char dsa512_priv[] = {
0x65, 0xe5, 0xc7, 0x38, 0x60, 0x24, 0xb5, 0x89, 0xd4, 0x9c, 0xeb, 0x4c,
0x9c, 0x1d, 0x7a, 0x22, 0xbd, 0xd1, 0xc2, 0xd2,
};
static unsigned char dsa512_pub[] = {
0x00, 0x95, 0xa7, 0x0d, 0xec, 0x93, 0x68, 0xba, 0x5f, 0xf7, 0x5f, 0x07,
0xf2, 0x3b, 0xad, 0x6b, 0x01, 0xdc, 0xbe, 0xec, 0xde, 0x04, 0x7a, 0x3a,
0x27, 0xb3, 0xec, 0x49, 0xfd, 0x08, 0x43, 0x3d, 0x7e, 0xa8, 0x2c, 0x5e,
0x7b, 0xbb, 0xfc, 0xf4, 0x6e, 0xeb, 0x6c, 0xb0, 0x6e, 0xf8, 0x02, 0x12,
0x8c, 0x38, 0x5d, 0x83, 0x56, 0x7d, 0xee, 0x53, 0x05, 0x3e, 0x24, 0x84,
0xbe, 0xba, 0x0a, 0x6b, 0xc8,
};
static unsigned char dsa512_p[] = {
0x9D, 0x1B, 0x69, 0x8E, 0x26, 0xDB, 0xF2, 0x2B, 0x11, 0x70, 0x19, 0x86,
0xF6, 0x19, 0xC8, 0xF8, 0x19, 0xF2, 0x18, 0x53, 0x94, 0x46, 0x06, 0xD0,
0x62, 0x50, 0x33, 0x4B, 0x02, 0x3C, 0x52, 0x30, 0x03, 0x8B, 0x3B, 0xF9,
0x5F, 0xD1, 0x24, 0x06, 0x4F, 0x7B, 0x4C, 0xBA, 0xAA, 0x40, 0x9B, 0xFD,
0x96, 0xE4, 0x37, 0x33, 0xBB, 0x2D, 0x5A, 0xD7, 0x5A, 0x11, 0x40, 0x66,
0xA2, 0x76, 0x7D, 0x31,
};
static unsigned char dsa512_q[] = {
0xFB, 0x53, 0xEF, 0x50, 0xB4, 0x40, 0x92, 0x31, 0x56, 0x86, 0x53, 0x7A,
0xE8, 0x8B, 0x22, 0x9A, 0x49, 0xFB, 0x71, 0x8F,
};
static unsigned char dsa512_g[] = {
0x83, 0x3E, 0x88, 0xE5, 0xC5, 0x89, 0x73, 0xCE, 0x3B, 0x6C, 0x01, 0x49,
0xBF, 0xB3, 0xC7, 0x9F, 0x0A, 0xEA, 0x44, 0x91, 0xE5, 0x30, 0xAA, 0xD9,
0xBE, 0x5B, 0x5F, 0xB7, 0x10, 0xD7, 0x89, 0xB7, 0x8E, 0x74, 0xFB, 0xCF,
0x29, 0x1E, 0xEB, 0xA8, 0x2C, 0x54, 0x51, 0xB8, 0x10, 0xDE, 0xA0, 0xCE,
0x2F, 0xCC, 0x24, 0x6B, 0x90, 0x77, 0xDE, 0xA2, 0x68, 0xA6, 0x52, 0x12,
0xA2, 0x03, 0x9D, 0x20,
};
static unsigned char dsa1024_priv[] = {
0x7d, 0x21, 0xda, 0xbb, 0x62, 0x15, 0x47, 0x36, 0x07, 0x67, 0x12, 0xe8,
0x8c, 0xaa, 0x1c, 0xcd, 0x38, 0x12, 0x61, 0x18,
};
static unsigned char dsa1024_pub[] = {
0x3c, 0x4e, 0x9c, 0x2a, 0x7f, 0x16, 0xc1, 0x25, 0xeb, 0xac, 0x78, 0x63,
0x90, 0x14, 0x8c, 0x8b, 0xf4, 0x68, 0x43, 0x3c, 0x2d, 0xee, 0x65, 0x50,
0x7d, 0x9c, 0x8f, 0x8c, 0x8a, 0x51, 0xd6, 0x11, 0x2b, 0x99, 0xaf, 0x1e,
0x90, 0x97, 0xb5, 0xd3, 0xa6, 0x20, 0x25, 0xd6, 0xfe, 0x43, 0x02, 0xd5,
0x91, 0x7d, 0xa7, 0x8c, 0xdb, 0xc9, 0x85, 0xa3, 0x36, 0x48, 0xf7, 0x68,
0xaa, 0x60, 0xb1, 0xf7, 0x05, 0x68, 0x3a, 0xa3, 0x3f, 0xd3, 0x19, 0x82,
0xd8, 0x82, 0x7a, 0x77, 0xfb, 0xef, 0xf4, 0x15, 0x0a, 0xeb, 0x06, 0x04,
0x7f, 0x53, 0x07, 0x0c, 0xbc, 0xcb, 0x2d, 0x83, 0xdb, 0x3e, 0xd1, 0x28,
0xa5, 0xa1, 0x31, 0xe0, 0x67, 0xfa, 0x50, 0xde, 0x9b, 0x07, 0x83, 0x7e,
0x2c, 0x0b, 0xc3, 0x13, 0x50, 0x61, 0xe5, 0xad, 0xbd, 0x36, 0xb8, 0x97,
0x4e, 0x40, 0x7d, 0xe8, 0x83, 0x0d, 0xbc, 0x4b
};
static unsigned char dsa1024_p[] = {
0xA7, 0x3F, 0x6E, 0x85, 0xBF, 0x41, 0x6A, 0x29, 0x7D, 0xF0, 0x9F, 0x47,
0x19, 0x30, 0x90, 0x9A, 0x09, 0x1D, 0xDA, 0x6A, 0x33, 0x1E, 0xC5, 0x3D,
0x86, 0x96, 0xB3, 0x15, 0xE0, 0x53, 0x2E, 0x8F, 0xE0, 0x59, 0x82, 0x73,
0x90, 0x3E, 0x75, 0x31, 0x99, 0x47, 0x7A, 0x52, 0xFB, 0x85, 0xE4, 0xD9,
0xA6, 0x7B, 0x38, 0x9B, 0x68, 0x8A, 0x84, 0x9B, 0x87, 0xC6, 0x1E, 0xB5,
0x7E, 0x86, 0x4B, 0x53, 0x5B, 0x59, 0xCF, 0x71, 0x65, 0x19, 0x88, 0x6E,
0xCE, 0x66, 0xAE, 0x6B, 0x88, 0x36, 0xFB, 0xEC, 0x28, 0xDC, 0xC2, 0xD7,
0xA5, 0xBB, 0xE5, 0x2C, 0x39, 0x26, 0x4B, 0xDA, 0x9A, 0x70, 0x18, 0x95,
0x37, 0x95, 0x10, 0x56, 0x23, 0xF6, 0x15, 0xED, 0xBA, 0x04, 0x5E, 0xDE,
0x39, 0x4F, 0xFD, 0xB7, 0x43, 0x1F, 0xB5, 0xA4, 0x65, 0x6F, 0xCD, 0x80,
0x11, 0xE4, 0x70, 0x95, 0x5B, 0x50, 0xCD, 0x49,
};
static unsigned char dsa1024_q[] = {
0xF7, 0x07, 0x31, 0xED, 0xFA, 0x6C, 0x06, 0x03, 0xD5, 0x85, 0x8A, 0x1C,
0xAC, 0x9C, 0x65, 0xE7, 0x50, 0x66, 0x65, 0x6F,
};
static unsigned char dsa1024_g[] = {
0x4D, 0xDF, 0x4C, 0x03, 0xA6, 0x91, 0x8A, 0xF5, 0x19, 0x6F, 0x50, 0x46,
0x25, 0x99, 0xE5, 0x68, 0x6F, 0x30, 0xE3, 0x69, 0xE1, 0xE5, 0xB3, 0x5D,
0x98, 0xBB, 0x28, 0x86, 0x48, 0xFC, 0xDE, 0x99, 0x04, 0x3F, 0x5F, 0x88,
0x0C, 0x9C, 0x73, 0x24, 0x0D, 0x20, 0x5D, 0xB9, 0x2A, 0x9A, 0x3F, 0x18,
0x96, 0x27, 0xE4, 0x62, 0x87, 0xC1, 0x7B, 0x74, 0x62, 0x53, 0xFC, 0x61,
0x27, 0xA8, 0x7A, 0x91, 0x09, 0x9D, 0xB6, 0xF1, 0x4D, 0x9C, 0x54, 0x0F,
0x58, 0x06, 0xEE, 0x49, 0x74, 0x07, 0xCE, 0x55, 0x7E, 0x23, 0xCE, 0x16,
0xF6, 0xCA, 0xDC, 0x5A, 0x61, 0x01, 0x7E, 0xC9, 0x71, 0xB5, 0x4D, 0xF6,
0xDC, 0x34, 0x29, 0x87, 0x68, 0xF6, 0x5E, 0x20, 0x93, 0xB3, 0xDB, 0xF5,
0xE4, 0x09, 0x6C, 0x41, 0x17, 0x95, 0x92, 0xEB, 0x01, 0xB5, 0x73, 0xA5,
0x6A, 0x7E, 0xD8, 0x32, 0xED, 0x0E, 0x02, 0xB8,
};
static unsigned char dsa2048_priv[] = {
0x32, 0x67, 0x92, 0xf6, 0xc4, 0xe2, 0xe2, 0xe8, 0xa0, 0x8b, 0x6b, 0x45,
0x0c, 0x8a, 0x76, 0xb0, 0xee, 0xcf, 0x91, 0xa7,
};
static unsigned char dsa2048_pub[] = {
0x17, 0x8f, 0xa8, 0x11, 0x84, 0x92, 0xec, 0x83, 0x47, 0xc7, 0x6a, 0xb0,
0x92, 0xaf, 0x5a, 0x20, 0x37, 0xa3, 0x64, 0x79, 0xd2, 0xd0, 0x3d, 0xcd,
0xe0, 0x61, 0x88, 0x88, 0x21, 0xcc, 0x74, 0x5d, 0xce, 0x4c, 0x51, 0x47,
0xf0, 0xc5, 0x5c, 0x4c, 0x82, 0x7a, 0xaf, 0x72, 0xad, 0xb9, 0xe0, 0x53,
0xf2, 0x78, 0xb7, 0xf0, 0xb5, 0x48, 0x7f, 0x8a, 0x3a, 0x18, 0xd1, 0x9f,
0x8b, 0x7d, 0xa5, 0x47, 0xb7, 0x95, 0xab, 0x98, 0xf8, 0x7b, 0x74, 0x50,
0x56, 0x8e, 0x57, 0xf0, 0xee, 0xf5, 0xb7, 0xba, 0xab, 0x85, 0x86, 0xf9,
0x2b, 0xef, 0x41, 0x56, 0xa0, 0xa4, 0x9f, 0xb7, 0x38, 0x00, 0x46, 0x0a,
0xa6, 0xf1, 0xfc, 0x1f, 0xd8, 0x4e, 0x85, 0x44, 0x92, 0x43, 0x21, 0x5d,
0x6e, 0xcc, 0xc2, 0xcb, 0x26, 0x31, 0x0d, 0x21, 0xc4, 0xbd, 0x8d, 0x24,
0xbc, 0xd9, 0x18, 0x19, 0xd7, 0xdc, 0xf1, 0xe7, 0x93, 0x50, 0x48, 0x03,
0x2c, 0xae, 0x2e, 0xe7, 0x49, 0x88, 0x5f, 0x93, 0x57, 0x27, 0x99, 0x36,
0xb4, 0x20, 0xab, 0xfc, 0xa7, 0x2b, 0xf2, 0xd9, 0x98, 0xd7, 0xd4, 0x34,
0x9d, 0x96, 0x50, 0x58, 0x9a, 0xea, 0x54, 0xf3, 0xee, 0xf5, 0x63, 0x14,
0xee, 0x85, 0x83, 0x74, 0x76, 0xe1, 0x52, 0x95, 0xc3, 0xf7, 0xeb, 0x04,
0x04, 0x7b, 0xa7, 0x28, 0x1b, 0xcc, 0xea, 0x4a, 0x4e, 0x84, 0xda, 0xd8,
0x9c, 0x79, 0xd8, 0x9b, 0x66, 0x89, 0x2f, 0xcf, 0xac, 0xd7, 0x79, 0xf9,
0xa9, 0xd8, 0x45, 0x13, 0x78, 0xb9, 0x00, 0x14, 0xc9, 0x7e, 0x22, 0x51,
0x86, 0x67, 0xb0, 0x9f, 0x26, 0x11, 0x23, 0xc8, 0x38, 0xd7, 0x70, 0x1d,
0x15, 0x8e, 0x4d, 0x4f, 0x95, 0x97, 0x40, 0xa1, 0xc2, 0x7e, 0x01, 0x18,
0x72, 0xf4, 0x10, 0xe6, 0x8d, 0x52, 0x16, 0x7f, 0xf2, 0xc9, 0xf8, 0x33,
0x8b, 0x33, 0xb7, 0xce,
};
static unsigned char dsa2048_p[] = {
0xA0, 0x25, 0xFA, 0xAD, 0xF4, 0x8E, 0xB9, 0xE5, 0x99, 0xF3, 0x5D, 0x6F,
0x4F, 0x83, 0x34, 0xE2, 0x7E, 0xCF, 0x6F, 0xBF, 0x30, 0xAF, 0x6F, 0x81,
0xEB, 0xF8, 0xC4, 0x13, 0xD9, 0xA0, 0x5D, 0x8B, 0x5C, 0x8E, 0xDC, 0xC2,
0x1D, 0x0B, 0x41, 0x32, 0xB0, 0x1F, 0xFE, 0xEF, 0x0C, 0xC2, 0xA2, 0x7E,
0x68, 0x5C, 0x28, 0x21, 0xE9, 0xF5, 0xB1, 0x58, 0x12, 0x63, 0x4C, 0x19,
0x4E, 0xFF, 0x02, 0x4B, 0x92, 0xED, 0xD2, 0x07, 0x11, 0x4D, 0x8C, 0x58,
0x16, 0x5C, 0x55, 0x8E, 0xAD, 0xA3, 0x67, 0x7D, 0xB9, 0x86, 0x6E, 0x0B,
0xE6, 0x54, 0x6F, 0x40, 0xAE, 0x0E, 0x67, 0x4C, 0xF9, 0x12, 0x5B, 0x3C,
0x08, 0x7A, 0xF7, 0xFC, 0x67, 0x86, 0x69, 0xE7, 0x0A, 0x94, 0x40, 0xBF,
0x8B, 0x76, 0xFE, 0x26, 0xD1, 0xF2, 0xA1, 0x1A, 0x84, 0xA1, 0x43, 0x56,
0x28, 0xBC, 0x9A, 0x5F, 0xD7, 0x3B, 0x69, 0x89, 0x8A, 0x36, 0x2C, 0x51,
0xDF, 0x12, 0x77, 0x2F, 0x57, 0x7B, 0xA0, 0xAA, 0xDD, 0x7F, 0xA1, 0x62,
0x3B, 0x40, 0x7B, 0x68, 0x1A, 0x8F, 0x0D, 0x38, 0xBB, 0x21, 0x5D, 0x18,
0xFC, 0x0F, 0x46, 0xF7, 0xA3, 0xB0, 0x1D, 0x23, 0xC3, 0xD2, 0xC7, 0x72,
0x51, 0x18, 0xDF, 0x46, 0x95, 0x79, 0xD9, 0xBD, 0xB5, 0x19, 0x02, 0x2C,
0x87, 0xDC, 0xE7, 0x57, 0x82, 0x7E, 0xF1, 0x8B, 0x06, 0x3D, 0x00, 0xA5,
0x7B, 0x6B, 0x26, 0x27, 0x91, 0x0F, 0x6A, 0x77, 0xE4, 0xD5, 0x04, 0xE4,
0x12, 0x2C, 0x42, 0xFF, 0xD2, 0x88, 0xBB, 0xD3, 0x92, 0xA0, 0xF9, 0xC8,
0x51, 0x64, 0x14, 0x5C, 0xD8, 0xF9, 0x6C, 0x47, 0x82, 0xB4, 0x1C, 0x7F,
0x09, 0xB8, 0xF0, 0x25, 0x83, 0x1D, 0x3F, 0x3F, 0x05, 0xB3, 0x21, 0x0A,
0x5D, 0xA7, 0xD8, 0x54, 0xC3, 0x65, 0x7D, 0xC3, 0xB0, 0x1D, 0xBF, 0xAE,
0xF8, 0x68, 0xCF, 0x9B,
};
static unsigned char dsa2048_q[] = {
0x97, 0xE7, 0x33, 0x4D, 0xD3, 0x94, 0x3E, 0x0B, 0xDB, 0x62, 0x74, 0xC6,
0xA1, 0x08, 0xDD, 0x19, 0xA3, 0x75, 0x17, 0x1B,
};
static unsigned char dsa2048_g[] = {
0x2C, 0x78, 0x16, 0x59, 0x34, 0x63, 0xF4, 0xF3, 0x92, 0xFC, 0xB5, 0xA5,
0x4F, 0x13, 0xDE, 0x2F, 0x1C, 0xA4, 0x3C, 0xAE, 0xAD, 0x38, 0x3F, 0x7E,
0x90, 0xBF, 0x96, 0xA6, 0xAE, 0x25, 0x90, 0x72, 0xF5, 0x8E, 0x80, 0x0C,
0x39, 0x1C, 0xD9, 0xEC, 0xBA, 0x90, 0x5B, 0x3A, 0xE8, 0x58, 0x6C, 0x9E,
0x30, 0x42, 0x37, 0x02, 0x31, 0x82, 0xBC, 0x6A, 0xDF, 0x6A, 0x09, 0x29,
0xE3, 0xC0, 0x46, 0xD1, 0xCB, 0x85, 0xEC, 0x0C, 0x30, 0x5E, 0xEA, 0xC8,
0x39, 0x8E, 0x22, 0x9F, 0x22, 0x10, 0xD2, 0x34, 0x61, 0x68, 0x37, 0x3D,
0x2E, 0x4A, 0x5B, 0x9A, 0xF5, 0xC1, 0x48, 0xC6, 0xF6, 0xDC, 0x63, 0x1A,
0xD3, 0x96, 0x64, 0xBA, 0x34, 0xC9, 0xD1, 0xA0, 0xD1, 0xAE, 0x6C, 0x2F,
0x48, 0x17, 0x93, 0x14, 0x43, 0xED, 0xF0, 0x21, 0x30, 0x19, 0xC3, 0x1B,
0x5F, 0xDE, 0xA3, 0xF0, 0x70, 0x78, 0x18, 0xE1, 0xA8, 0xE4, 0xEE, 0x2E,
0x00, 0xA5, 0xE4, 0xB3, 0x17, 0xC8, 0x0C, 0x7D, 0x6E, 0x42, 0xDC, 0xB7,
0x46, 0x00, 0x36, 0x4D, 0xD4, 0x46, 0xAA, 0x3D, 0x3C, 0x46, 0x89, 0x40,
0xBF, 0x1D, 0x84, 0x77, 0x0A, 0x75, 0xF3, 0x87, 0x1D, 0x08, 0x4C, 0xA6,
0xD1, 0xA9, 0x1C, 0x1E, 0x12, 0x1E, 0xE1, 0xC7, 0x30, 0x28, 0x76, 0xA5,
0x7F, 0x6C, 0x85, 0x96, 0x2B, 0x6F, 0xDB, 0x80, 0x66, 0x26, 0xAE, 0xF5,
0x93, 0xC7, 0x8E, 0xAE, 0x9A, 0xED, 0xE4, 0xCA, 0x04, 0xEA, 0x3B, 0x72,
0xEF, 0xDC, 0x87, 0xED, 0x0D, 0xA5, 0x4C, 0x4A, 0xDD, 0x71, 0x22, 0x64,
0x59, 0x69, 0x4E, 0x8E, 0xBF, 0x43, 0xDC, 0xAB, 0x8E, 0x66, 0xBB, 0x01,
0xB6, 0xF4, 0xE7, 0xFD, 0xD2, 0xAD, 0x9F, 0x36, 0xC1, 0xA0, 0x29, 0x99,
0xD1, 0x96, 0x70, 0x59, 0x06, 0x78, 0x35, 0xBD, 0x65, 0x55, 0x52, 0x9E,
0xF8, 0xB2, 0xE5, 0x38,
};
typedef struct testdsa_st {
unsigned char *priv;
unsigned char *pub;
unsigned char *p;
unsigned char *g;
unsigned char *q;
int priv_l;
int pub_l;
int p_l;
int g_l;
int q_l;
} testdsa;
#define set_dsa_ptr(st, bits) \
do { \
st.priv = dsa##bits##_priv; \
st.pub = dsa##bits##_pub; \
st.p = dsa##bits##_p; \
st.g = dsa##bits##_g; \
st.q = dsa##bits##_q; \
st.priv_l = sizeof(dsa##bits##_priv); \
st.pub_l = sizeof(dsa##bits##_pub); \
st.p_l = sizeof(dsa##bits##_p); \
st.g_l = sizeof(dsa##bits##_g); \
st.q_l = sizeof(dsa##bits##_q); \
} while (0)
EVP_PKEY *get_dsa(int dsa_bits)
{
EVP_PKEY *pkey = NULL;
BIGNUM *priv_key, *pub_key, *p, *q, *g;
EVP_PKEY_CTX *pctx;
testdsa dsa_t;
OSSL_PARAM_BLD *tmpl = NULL;
OSSL_PARAM *params = NULL;
switch (dsa_bits) {
case 512:
set_dsa_ptr(dsa_t, 512);
break;
case 1024:
set_dsa_ptr(dsa_t, 1024);
break;
case 2048:
set_dsa_ptr(dsa_t, 2048);
break;
default:
return NULL;
}
if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL)) == NULL)
return NULL;
priv_key = BN_bin2bn(dsa_t.priv, dsa_t.priv_l, NULL);
pub_key = BN_bin2bn(dsa_t.pub, dsa_t.pub_l, NULL);
p = BN_bin2bn(dsa_t.p, dsa_t.p_l, NULL);
q = BN_bin2bn(dsa_t.q, dsa_t.q_l, NULL);
g = BN_bin2bn(dsa_t.g, dsa_t.g_l, NULL);
if (priv_key == NULL || pub_key == NULL || p == NULL || q == NULL
|| g == NULL) {
goto err;
}
if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P,
p)
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q,
q)
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G,
g)
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PRIV_KEY,
priv_key)
|| !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY,
pub_key)
|| (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL)
goto err;
if (EVP_PKEY_fromdata_init(pctx) <= 0
|| EVP_PKEY_fromdata(pctx, &pkey, EVP_PKEY_KEYPAIR,
params) <= 0)
pkey = NULL;
err:
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(tmpl);
BN_free(priv_key);
BN_free(pub_key);
BN_free(p);
BN_free(q);
BN_free(g);
EVP_PKEY_CTX_free(pctx);
return pkey;
}
| 12,977 | 45.35 | 75 |
h
|
openssl
|
openssl-master/apps/timeouts.h
|
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_TIMEOUTS_H
# define OSSL_APPS_TIMEOUTS_H
/* numbers in us */
# define DGRAM_RCV_TIMEOUT 250000
# define DGRAM_SND_TIMEOUT 250000
#endif /* ! OSSL_APPS_TIMEOUTS_H */
| 563 | 30.333333 | 74 |
h
|
openssl
|
openssl-master/apps/verify.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
static int cb(int ok, X509_STORE_CTX *ctx);
static int check(X509_STORE *ctx, const char *file,
STACK_OF(X509) *uchain, STACK_OF(X509) *tchain,
STACK_OF(X509_CRL) *crls, int show_chain,
STACK_OF(OPENSSL_STRING) *opts);
static int v_verbose = 0, vflags = 0;
typedef enum OPTION_choice {
OPT_COMMON,
OPT_ENGINE, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE,
OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
OPT_UNTRUSTED, OPT_TRUSTED, OPT_CRLFILE, OPT_CRL_DOWNLOAD, OPT_SHOW_CHAIN,
OPT_V_ENUM, OPT_NAMEOPT, OPT_VFYOPT,
OPT_VERBOSE,
OPT_PROV_ENUM
} OPTION_CHOICE;
const OPTIONS verify_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
{"verbose", OPT_VERBOSE, '-',
"Print extra information about the operations being performed."},
{"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
OPT_SECTION("Certificate chain"),
{"trusted", OPT_TRUSTED, '<', "A file of trusted certificates"},
{"CAfile", OPT_CAFILE, '<', "A file of trusted certificates"},
{"CApath", OPT_CAPATH, '/', "A directory of files with trusted certificates"},
{"CAstore", OPT_CASTORE, ':', "URI to a store of trusted certificates"},
{"no-CAfile", OPT_NOCAFILE, '-',
"Do not load the default trusted certificates file"},
{"no-CApath", OPT_NOCAPATH, '-',
"Do not load trusted certificates from the default directory"},
{"no-CAstore", OPT_NOCASTORE, '-',
"Do not load trusted certificates from the default certificates store"},
{"untrusted", OPT_UNTRUSTED, '<', "A file of untrusted certificates"},
{"CRLfile", OPT_CRLFILE, '<',
"File containing one or more CRL's (in PEM format) to load"},
{"crl_download", OPT_CRL_DOWNLOAD, '-',
"Try downloading CRL information for certificates via their CDP entries"},
{"show_chain", OPT_SHOW_CHAIN, '-',
"Display information about the certificate chain"},
OPT_V_OPTIONS,
{"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"cert", 0, 0, "Certificate(s) to verify (optional; stdin used otherwise)"},
{NULL}
};
int verify_main(int argc, char **argv)
{
ENGINE *e = NULL;
STACK_OF(X509) *untrusted = NULL, *trusted = NULL;
STACK_OF(X509_CRL) *crls = NULL;
STACK_OF(OPENSSL_STRING) *vfyopts = NULL;
X509_STORE *store = NULL;
X509_VERIFY_PARAM *vpm = NULL;
const char *prog, *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
int noCApath = 0, noCAfile = 0, noCAstore = 0;
int vpmtouched = 0, crl_download = 0, show_chain = 0, i = 0, ret = 1;
OPTION_CHOICE o;
if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
goto end;
prog = opt_init(argc, argv, verify_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(verify_options);
BIO_printf(bio_err, "\nRecognized certificate chain purposes:\n");
for (i = 0; i < X509_PURPOSE_get_count(); i++) {
X509_PURPOSE *ptmp = X509_PURPOSE_get0(i);
BIO_printf(bio_err, " %-15s %s\n",
X509_PURPOSE_get0_sname(ptmp),
X509_PURPOSE_get0_name(ptmp));
}
BIO_printf(bio_err, "Recognized certificate policy names:\n");
for (i = 0; i < X509_VERIFY_PARAM_get_count(); i++) {
const X509_VERIFY_PARAM *vptmp = X509_VERIFY_PARAM_get0(i);
BIO_printf(bio_err, " %s\n",
X509_VERIFY_PARAM_get0_name(vptmp));
}
ret = 0;
goto end;
case OPT_V_CASES:
if (!opt_verify(o, vpm))
goto end;
vpmtouched++;
break;
case OPT_CAPATH:
CApath = opt_arg();
break;
case OPT_CAFILE:
CAfile = opt_arg();
break;
case OPT_CASTORE:
CAstore = opt_arg();
break;
case OPT_NOCAPATH:
noCApath = 1;
break;
case OPT_NOCAFILE:
noCAfile = 1;
break;
case OPT_NOCASTORE:
noCAstore = 1;
break;
case OPT_UNTRUSTED:
/* Zero or more times */
if (!load_certs(opt_arg(), 0, &untrusted, NULL,
"untrusted certificates"))
goto end;
break;
case OPT_TRUSTED:
/* Zero or more times */
noCAfile = 1;
noCApath = 1;
noCAstore = 1;
if (!load_certs(opt_arg(), 0, &trusted, NULL, "trusted certificates"))
goto end;
break;
case OPT_CRLFILE:
/* Zero or more times */
if (!load_crls(opt_arg(), &crls, NULL, "other CRLs"))
goto end;
break;
case OPT_CRL_DOWNLOAD:
crl_download = 1;
break;
case OPT_ENGINE:
if ((e = setup_engine(opt_arg(), 0)) == NULL) {
/* Failure message already displayed */
goto end;
}
break;
case OPT_SHOW_CHAIN:
show_chain = 1;
break;
case OPT_NAMEOPT:
if (!set_nameopt(opt_arg()))
goto end;
break;
case OPT_VFYOPT:
if (!vfyopts)
vfyopts = sk_OPENSSL_STRING_new_null();
if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
goto opthelp;
break;
case OPT_VERBOSE:
v_verbose = 1;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
}
}
/* Extra arguments are certificates to verify. */
argc = opt_num_rest();
argv = opt_rest();
if (trusted != NULL
&& (CAfile != NULL || CApath != NULL || CAstore != NULL)) {
BIO_printf(bio_err,
"%s: Cannot use -trusted with -CAfile, -CApath or -CAstore\n",
prog);
goto end;
}
if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
CAstore, noCAstore)) == NULL)
goto end;
X509_STORE_set_verify_cb(store, cb);
if (vpmtouched)
X509_STORE_set1_param(store, vpm);
ERR_clear_error();
if (crl_download)
store_setup_crl_download(store);
ret = 0;
if (argc < 1) {
if (check(store, NULL, untrusted, trusted, crls, show_chain,
vfyopts) != 1)
ret = -1;
} else {
for (i = 0; i < argc; i++)
if (check(store, argv[i], untrusted, trusted, crls, show_chain,
vfyopts) != 1)
ret = -1;
}
end:
X509_VERIFY_PARAM_free(vpm);
X509_STORE_free(store);
OSSL_STACK_OF_X509_free(untrusted);
OSSL_STACK_OF_X509_free(trusted);
sk_X509_CRL_pop_free(crls, X509_CRL_free);
sk_OPENSSL_STRING_free(vfyopts);
release_engine(e);
return (ret < 0 ? 2 : ret);
}
static int check(X509_STORE *ctx, const char *file,
STACK_OF(X509) *uchain, STACK_OF(X509) *tchain,
STACK_OF(X509_CRL) *crls, int show_chain,
STACK_OF(OPENSSL_STRING) *opts)
{
X509 *x = NULL;
int i = 0, ret = 0;
X509_STORE_CTX *csc;
STACK_OF(X509) *chain = NULL;
int num_untrusted;
x = load_cert(file, FORMAT_UNDEF, "certificate file");
if (x == NULL)
goto end;
if (opts != NULL) {
for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
char *opt = sk_OPENSSL_STRING_value(opts, i);
if (x509_ctrl_string(x, opt) <= 0) {
BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
ERR_print_errors(bio_err);
X509_free(x);
return 0;
}
}
}
csc = X509_STORE_CTX_new();
if (csc == NULL) {
BIO_printf(bio_err, "error %s: X.509 store context allocation failed\n",
(file == NULL) ? "stdin" : file);
goto end;
}
X509_STORE_set_flags(ctx, vflags);
if (!X509_STORE_CTX_init(csc, ctx, x, uchain)) {
X509_STORE_CTX_free(csc);
BIO_printf(bio_err,
"error %s: X.509 store context initialization failed\n",
(file == NULL) ? "stdin" : file);
goto end;
}
if (tchain != NULL)
X509_STORE_CTX_set0_trusted_stack(csc, tchain);
if (crls != NULL)
X509_STORE_CTX_set0_crls(csc, crls);
i = X509_verify_cert(csc);
if (i > 0 && X509_STORE_CTX_get_error(csc) == X509_V_OK) {
BIO_printf(bio_out, "%s: OK\n", (file == NULL) ? "stdin" : file);
ret = 1;
if (show_chain) {
int j;
chain = X509_STORE_CTX_get1_chain(csc);
num_untrusted = X509_STORE_CTX_get_num_untrusted(csc);
BIO_printf(bio_out, "Chain:\n");
for (j = 0; j < sk_X509_num(chain); j++) {
X509 *cert = sk_X509_value(chain, j);
BIO_printf(bio_out, "depth=%d: ", j);
X509_NAME_print_ex_fp(stdout,
X509_get_subject_name(cert),
0, get_nameopt());
if (j < num_untrusted)
BIO_printf(bio_out, " (untrusted)");
BIO_printf(bio_out, "\n");
}
OSSL_STACK_OF_X509_free(chain);
}
} else {
BIO_printf(bio_err,
"error %s: verification failed\n",
(file == NULL) ? "stdin" : file);
}
X509_STORE_CTX_free(csc);
end:
if (i <= 0)
ERR_print_errors(bio_err);
X509_free(x);
return ret;
}
static int cb(int ok, X509_STORE_CTX *ctx)
{
int cert_error = X509_STORE_CTX_get_error(ctx);
X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx);
if (!ok) {
if (current_cert != NULL) {
X509_NAME_print_ex(bio_err,
X509_get_subject_name(current_cert),
0, get_nameopt());
BIO_printf(bio_err, "\n");
}
BIO_printf(bio_err, "%serror %d at %d depth lookup: %s\n",
X509_STORE_CTX_get0_parent_ctx(ctx) ? "[CRL path] " : "",
cert_error,
X509_STORE_CTX_get_error_depth(ctx),
X509_verify_cert_error_string(cert_error));
/*
* Pretend that some errors are ok, so they don't stop further
* processing of the certificate chain. Setting ok = 1 does this.
* After X509_verify_cert() is done, we verify that there were
* no actual errors, even if the returned value was positive.
*/
switch (cert_error) {
case X509_V_ERR_NO_EXPLICIT_POLICY:
policies_print(ctx);
/* fall through */
case X509_V_ERR_CERT_HAS_EXPIRED:
/* Continue even if the leaf is a self-signed cert */
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
/* Continue after extension errors too */
case X509_V_ERR_INVALID_CA:
case X509_V_ERR_INVALID_NON_CA:
case X509_V_ERR_PATH_LENGTH_EXCEEDED:
case X509_V_ERR_CRL_HAS_EXPIRED:
case X509_V_ERR_CRL_NOT_YET_VALID:
case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
/* errors due to strict conformance checking (-x509_strict) */
case X509_V_ERR_INVALID_PURPOSE:
case X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA:
case X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN:
case X509_V_ERR_CA_BCONS_NOT_CRITICAL:
case X509_V_ERR_CA_CERT_MISSING_KEY_USAGE:
case X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA:
case X509_V_ERR_ISSUER_NAME_EMPTY:
case X509_V_ERR_SUBJECT_NAME_EMPTY:
case X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL:
case X509_V_ERR_EMPTY_SUBJECT_ALT_NAME:
case X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY:
case X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL:
case X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL:
case X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER:
case X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER:
case X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3:
ok = 1;
}
return ok;
}
if (cert_error == X509_V_OK && ok == 2)
policies_print(ctx);
if (!v_verbose)
ERR_clear_error();
return ok;
}
| 13,529 | 33.340102 | 86 |
c
|
openssl
|
openssl-master/apps/version.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include "progs.h"
#include <openssl/evp.h>
#include <openssl/crypto.h>
#include <openssl/bn.h>
typedef enum OPTION_choice {
OPT_COMMON,
OPT_B, OPT_D, OPT_E, OPT_M, OPT_F, OPT_O, OPT_P, OPT_V, OPT_A, OPT_R, OPT_C
} OPTION_CHOICE;
const OPTIONS version_options[] = {
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
OPT_SECTION("Output"),
{"a", OPT_A, '-', "Show all data"},
{"b", OPT_B, '-', "Show build date"},
{"d", OPT_D, '-', "Show configuration directory"},
{"e", OPT_E, '-', "Show engines directory"},
{"m", OPT_M, '-', "Show modules directory"},
{"f", OPT_F, '-', "Show compiler flags used"},
{"o", OPT_O, '-', "Show some internal datatype options"},
{"p", OPT_P, '-', "Show target build platform"},
{"r", OPT_R, '-', "Show random seeding options"},
{"v", OPT_V, '-', "Show library version"},
{"c", OPT_C, '-', "Show CPU settings info"},
{NULL}
};
int version_main(int argc, char **argv)
{
int ret = 1, dirty = 0, seed = 0;
int cflags = 0, version = 0, date = 0, options = 0, platform = 0, dir = 0;
int engdir = 0, moddir = 0, cpuinfo = 0;
char *prog;
OPTION_CHOICE o;
prog = opt_init(argc, argv, version_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(version_options);
ret = 0;
goto end;
case OPT_B:
dirty = date = 1;
break;
case OPT_D:
dirty = dir = 1;
break;
case OPT_E:
dirty = engdir = 1;
break;
case OPT_M:
dirty = moddir = 1;
break;
case OPT_F:
dirty = cflags = 1;
break;
case OPT_O:
dirty = options = 1;
break;
case OPT_P:
dirty = platform = 1;
break;
case OPT_R:
dirty = seed = 1;
break;
case OPT_V:
dirty = version = 1;
break;
case OPT_C:
dirty = cpuinfo = 1;
break;
case OPT_A:
seed = options = cflags = version = date = platform
= dir = engdir = moddir = cpuinfo
= 1;
break;
}
}
/* No extra arguments. */
if (!opt_check_rest_arg(NULL))
goto opthelp;
if (!dirty)
version = 1;
if (version)
printf("%s (Library: %s)\n",
OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION));
if (date)
printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON));
if (platform)
printf("%s\n", OpenSSL_version(OPENSSL_PLATFORM));
if (options) {
printf("options: ");
printf(" %s", BN_options());
printf("\n");
}
if (cflags)
printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS));
if (dir)
printf("%s\n", OpenSSL_version(OPENSSL_DIR));
if (engdir)
printf("%s\n", OpenSSL_version(OPENSSL_ENGINES_DIR));
if (moddir)
printf("%s\n", OpenSSL_version(OPENSSL_MODULES_DIR));
if (seed) {
const char *src = OPENSSL_info(OPENSSL_INFO_SEED_SOURCE);
printf("Seeding source: %s\n", src ? src : "N/A");
}
if (cpuinfo)
printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO));
ret = 0;
end:
return ret;
}
#if defined(__TANDEM) && defined(OPENSSL_VPROC)
/*
* Define a VPROC function for the openssl program.
* This is used by platform version identification tools.
* Do not inline this procedure or make it static.
*/
# define OPENSSL_VPROC_STRING_(x) x##_OPENSSL
# define OPENSSL_VPROC_STRING(x) OPENSSL_VPROC_STRING_(x)
# define OPENSSL_VPROC_FUNC OPENSSL_VPROC_STRING(OPENSSL_VPROC)
void OPENSSL_VPROC_FUNC(void) {}
#endif
| 4,383 | 28.033113 | 79 |
c
|
openssl
|
openssl-master/apps/vms_decc_init.c
|
/*
* Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#if defined( __VMS) && !defined( OPENSSL_NO_DECC_INIT) && \
defined( __DECC) && !defined( __VAX) && (__CRTL_VER >= 70301000)
# define USE_DECC_INIT 1
#endif
#ifdef USE_DECC_INIT
/*
* ----------------------------------------------------------------------
* decc_init() On non-VAX systems, uses LIB$INITIALIZE to set a collection
* of C RTL features without using the DECC$* logical name method.
* ----------------------------------------------------------------------
*/
# include <stdio.h>
# include <stdlib.h>
# include <unixlib.h>
/* Global storage. */
/* Flag to sense if decc_init() was called. */
int decc_init_done = -1;
/* Structure to hold a DECC$* feature name and its desired value. */
typedef struct {
char *name;
int value;
} decc_feat_t;
/*
* Array of DECC$* feature names and their desired values. Note:
* DECC$ARGV_PARSE_STYLE is the urgent one.
*/
decc_feat_t decc_feat_array[] = {
/* Preserve command-line case with SET PROCESS/PARSE_STYLE=EXTENDED */
{"DECC$ARGV_PARSE_STYLE", 1},
/* Preserve case for file names on ODS5 disks. */
{"DECC$EFS_CASE_PRESERVE", 1},
/*
* Enable multiple dots (and most characters) in ODS5 file names, while
* preserving VMS-ness of ";version".
*/
{"DECC$EFS_CHARSET", 1},
/* List terminator. */
{(char *)NULL, 0}
};
/* LIB$INITIALIZE initialization function. */
static void decc_init(void)
{
char *openssl_debug_decc_init;
int verbose = 0;
int feat_index;
int feat_value;
int feat_value_max;
int feat_value_min;
int i;
int sts;
/* Get debug option. */
openssl_debug_decc_init = getenv("OPENSSL_DEBUG_DECC_INIT");
if (openssl_debug_decc_init != NULL) {
verbose = strtol(openssl_debug_decc_init, NULL, 10);
if (verbose <= 0) {
verbose = 1;
}
}
/* Set the global flag to indicate that LIB$INITIALIZE worked. */
decc_init_done = 1;
/* Loop through all items in the decc_feat_array[]. */
for (i = 0; decc_feat_array[i].name != NULL; i++) {
/* Get the feature index. */
feat_index = decc$feature_get_index(decc_feat_array[i].name);
if (feat_index >= 0) {
/* Valid item. Collect its properties. */
feat_value = decc$feature_get_value(feat_index, 1);
feat_value_min = decc$feature_get_value(feat_index, 2);
feat_value_max = decc$feature_get_value(feat_index, 3);
/* Check the validity of our desired value. */
if ((decc_feat_array[i].value >= feat_value_min) &&
(decc_feat_array[i].value <= feat_value_max)) {
/* Valid value. Set it if necessary. */
if (feat_value != decc_feat_array[i].value) {
sts = decc$feature_set_value(feat_index,
1, decc_feat_array[i].value);
if (verbose > 1) {
fprintf(stderr, " %s = %d, sts = %d.\n",
decc_feat_array[i].name,
decc_feat_array[i].value, sts);
}
}
} else {
/* Invalid DECC feature value. */
fprintf(stderr,
" INVALID DECC$FEATURE VALUE, %d: %d <= %s <= %d.\n",
feat_value,
feat_value_min, decc_feat_array[i].name,
feat_value_max);
}
} else {
/* Invalid DECC feature name. */
fprintf(stderr,
" UNKNOWN DECC$FEATURE: %s.\n", decc_feat_array[i].name);
}
}
if (verbose > 0) {
fprintf(stderr, " DECC_INIT complete.\n");
}
}
/* Get "decc_init()" into a valid, loaded LIB$INITIALIZE PSECT. */
# pragma nostandard
/*
* Establish the LIB$INITIALIZE PSECTs, with proper alignment and other
* attributes. Note that "nopic" is significant only on VAX.
*/
# pragma extern_model save
# if __INITIAL_POINTER_SIZE == 64
# define PSECT_ALIGN 3
# else
# define PSECT_ALIGN 2
# endif
# pragma extern_model strict_refdef "LIB$INITIALIZ" PSECT_ALIGN, nopic, nowrt
const int spare[8] = { 0 };
# pragma extern_model strict_refdef "LIB$INITIALIZE" PSECT_ALIGN, nopic, nowrt
void (*const x_decc_init) () = decc_init;
# pragma extern_model restore
/* Fake reference to ensure loading the LIB$INITIALIZE PSECT. */
# pragma extern_model save
int LIB$INITIALIZE(void);
# pragma extern_model strict_refdef
int dmy_lib$initialize = (int)LIB$INITIALIZE;
# pragma extern_model restore
# pragma standard
#else /* def USE_DECC_INIT */
/* Dummy code to avoid a %CC-W-EMPTYFILE complaint. */
int decc_init_dummy(void);
#endif /* def USE_DECC_INIT */
| 5,180 | 28.271186 | 78 |
c
|
openssl
|
openssl-master/apps/include/app_libctx.h
|
/*
* Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_LIBCTX_H
# define OSSL_APPS_LIBCTX_H
# include <openssl/types.h>
OSSL_LIB_CTX *app_create_libctx(void);
OSSL_LIB_CTX *app_get0_libctx(void);
int app_set_propq(const char *arg);
const char *app_get0_propq(void);
#endif
| 571 | 26.238095 | 74 |
h
|
openssl
|
openssl-master/apps/include/app_params.h
|
/*
* Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/core.h>
int print_param_types(const char *thing, const OSSL_PARAM *pdefs, int indent);
void print_param_value(const OSSL_PARAM *p, int indent);
| 501 | 32.466667 | 78 |
h
|
openssl
|
openssl-master/apps/include/apps.h
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_H
# define OSSL_APPS_H
# include "internal/e_os.h" /* struct timeval for DTLS */
# include "internal/common.h" /* for HAS_PREFIX */
# include "internal/nelem.h"
# include "internal/sockets.h" /* for openssl_fdset() */
# include <assert.h>
# include <stdarg.h>
# include <sys/types.h>
# ifndef OPENSSL_NO_POSIX_IO
# include <sys/stat.h>
# include <fcntl.h>
# endif
# include <openssl/e_os2.h>
# include <openssl/types.h>
# include <openssl/bio.h>
# include <openssl/x509.h>
# include <openssl/conf.h>
# include <openssl/txt_db.h>
# include <openssl/engine.h>
# include <openssl/ocsp.h>
# include <openssl/http.h>
# include <signal.h>
# include "apps_ui.h"
# include "opt.h"
# include "fmt.h"
# include "platform.h"
# include "engine_loader.h"
# include "app_libctx.h"
/*
* quick macro when you need to pass an unsigned char instead of a char.
* this is true for some implementations of the is*() functions, for
* example.
*/
# define _UC(c) ((unsigned char)(c))
void app_RAND_load_conf(CONF *c, const char *section);
int app_RAND_write(void);
int app_RAND_load(void);
extern char *default_config_file; /* may be "" */
extern BIO *bio_in;
extern BIO *bio_out;
extern BIO *bio_err;
extern const unsigned char tls13_aes128gcmsha256_id[];
extern const unsigned char tls13_aes256gcmsha384_id[];
extern BIO_ADDR *ourpeer;
BIO *dup_bio_in(int format);
BIO *dup_bio_out(int format);
BIO *dup_bio_err(int format);
BIO *bio_open_owner(const char *filename, int format, int private);
BIO *bio_open_default(const char *filename, char mode, int format);
BIO *bio_open_default_quiet(const char *filename, char mode, int format);
char *app_conf_try_string(const CONF *cnf, const char *group, const char *name);
int app_conf_try_number(const CONF *conf, const char *group, const char *name,
long *result);
CONF *app_load_config_bio(BIO *in, const char *filename);
# define app_load_config(filename) app_load_config_internal(filename, 0)
# define app_load_config_quiet(filename) app_load_config_internal(filename, 1)
CONF *app_load_config_internal(const char *filename, int quiet);
CONF *app_load_config_verbose(const char *filename, int verbose);
int app_load_modules(const CONF *config);
CONF *app_load_config_modules(const char *configfile);
void unbuffer(FILE *fp);
void wait_for_async(SSL *s);
# if defined(OPENSSL_SYS_MSDOS)
int has_stdin_waiting(void);
# endif
void corrupt_signature(const ASN1_STRING *signature);
int set_cert_times(X509 *x, const char *startdate, const char *enddate,
int days);
int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate);
int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
long days, long hours, long secs);
typedef struct args_st {
int size;
int argc;
char **argv;
} ARGS;
/* We need both wrap and the "real" function because libcrypto uses both. */
int wrap_password_callback(char *buf, int bufsiz, int verify, void *cb_data);
/* progress callback for dsaparam, dhparam, req, genpkey, etc. */
int progress_cb(EVP_PKEY_CTX *ctx);
int chopup_args(ARGS *arg, char *buf);
void dump_cert_text(BIO *out, X509 *x);
void print_name(BIO *out, const char *title, const X509_NAME *nm);
void print_bignum_var(BIO *, const BIGNUM *, const char *,
int, unsigned char *);
void print_array(BIO *, const char *, int, const unsigned char *);
int set_nameopt(const char *arg);
unsigned long get_nameopt(void);
int set_dateopt(unsigned long *dateopt, const char *arg);
int set_cert_ex(unsigned long *flags, const char *arg);
int set_name_ex(unsigned long *flags, const char *arg);
int set_ext_copy(int *copy_type, const char *arg);
int copy_extensions(X509 *x, X509_REQ *req, int copy_type);
char *get_passwd(const char *pass, const char *desc);
int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2);
int add_oid_section(CONF *conf);
X509_REQ *load_csr(const char *file, int format, const char *desc);
X509_REQ *load_csr_autofmt(const char *infile, int format,
STACK_OF(OPENSSL_STRING) *vfyopts, const char *desc);
X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
const char *pass, const char *desc);
# define load_cert(uri, format, desc) load_cert_pass(uri, format, 1, NULL, desc)
X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
const char *desc);
void cleanse(char *str);
void clear_free(char *str);
EVP_PKEY *load_key(const char *uri, int format, int maybe_stdin,
const char *pass, ENGINE *e, const char *desc);
/* first try reading public key, on failure resort to loading private key */
EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
const char *pass, ENGINE *e, const char *desc);
EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
const char *keytype, const char *desc);
EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
const char *keytype, const char *desc,
int suppress_decode_errors);
char *next_item(char *opt); /* in list separated by comma and/or space */
int load_cert_certs(const char *uri,
X509 **pcert, STACK_OF(X509) **pcerts,
int exclude_http, const char *pass, const char *desc,
X509_VERIFY_PARAM *vpm);
STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
const char *desc, X509_VERIFY_PARAM *vpm);
X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
X509_VERIFY_PARAM *vpm);
int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
const char *pass, const char *desc);
int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
const char *pass, const char *desc);
int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
const char *pass, const char *desc, int quiet,
EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
EVP_PKEY **pparams,
X509 **pcert, STACK_OF(X509) **pcerts,
X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls);
X509_STORE *setup_verify(const char *CAfile, int noCAfile,
const char *CApath, int noCApath,
const char *CAstore, int noCAstore);
__owur int ctx_set_verify_locations(SSL_CTX *ctx,
const char *CAfile, int noCAfile,
const char *CApath, int noCApath,
const char *CAstore, int noCAstore);
# ifndef OPENSSL_NO_CT
/*
* Sets the file to load the Certificate Transparency log list from.
* If path is NULL, loads from the default file path.
* Returns 1 on success, 0 otherwise.
*/
__owur int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path);
# endif
ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug);
# define setup_engine(e, debug) setup_engine_methods(e, (unsigned int)-1, debug)
void release_engine(ENGINE *e);
int init_engine(ENGINE *e);
int finish_engine(ENGINE *e);
char *make_engine_uri(ENGINE *e, const char *key_id, const char *desc);
int get_legacy_pkey_id(OSSL_LIB_CTX *libctx, const char *algname, ENGINE *e);
const EVP_MD *get_digest_from_engine(const char *name);
const EVP_CIPHER *get_cipher_from_engine(const char *name);
# ifndef OPENSSL_NO_OCSP
OCSP_RESPONSE *process_responder(OCSP_REQUEST *req, const char *host,
const char *port, const char *path,
const char *proxy, const char *no_proxy,
int use_ssl, STACK_OF(CONF_VALUE) *headers,
int req_timeout);
# endif
/* Functions defined in ca.c and also used in ocsp.c */
int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold,
ASN1_GENERALIZEDTIME **pinvtm, const char *str);
# define DB_type 0
# define DB_exp_date 1
# define DB_rev_date 2
# define DB_serial 3 /* index - unique */
# define DB_file 4
# define DB_name 5 /* index - unique when active and not disabled */
# define DB_NUMBER 6
# define DB_TYPE_REV 'R' /* Revoked */
# define DB_TYPE_EXP 'E' /* Expired */
# define DB_TYPE_VAL 'V' /* Valid ; inserted with: ca ... -valid */
# define DB_TYPE_SUSP 'S' /* Suspended */
typedef struct db_attr_st {
int unique_subject;
} DB_ATTR;
typedef struct ca_db_st {
DB_ATTR attributes;
TXT_DB *db;
char *dbfname;
# ifndef OPENSSL_NO_POSIX_IO
struct stat dbst;
# endif
} CA_DB;
extern int do_updatedb(CA_DB *db, time_t *now);
void app_bail_out(char *fmt, ...);
void *app_malloc(size_t sz, const char *what);
/* load_serial, save_serial, and rotate_serial are also used for CRL numbers */
BIGNUM *load_serial(const char *serialfile, int *exists, int create,
ASN1_INTEGER **retai);
int save_serial(const char *serialfile, const char *suffix,
const BIGNUM *serial, ASN1_INTEGER **retai);
int rotate_serial(const char *serialfile, const char *new_suffix,
const char *old_suffix);
int rand_serial(BIGNUM *b, ASN1_INTEGER *ai);
CA_DB *load_index(const char *dbfile, DB_ATTR *dbattr);
int index_index(CA_DB *db);
int save_index(const char *dbfile, const char *suffix, CA_DB *db);
int rotate_index(const char *dbfile, const char *new_suffix,
const char *old_suffix);
void free_index(CA_DB *db);
# define index_name_cmp_noconst(a, b) \
index_name_cmp((const OPENSSL_CSTRING *)CHECKED_PTR_OF(OPENSSL_STRING, a), \
(const OPENSSL_CSTRING *)CHECKED_PTR_OF(OPENSSL_STRING, b))
int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b);
int parse_yesno(const char *str, int def);
X509_NAME *parse_name(const char *str, int chtype, int multirdn,
const char *desc);
void policies_print(X509_STORE_CTX *ctx);
int bio_to_mem(unsigned char **out, int maxlen, BIO *in);
int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value);
int x509_ctrl_string(X509 *x, const char *value);
int x509_req_ctrl_string(X509_REQ *x, const char *value);
int init_gen_str(EVP_PKEY_CTX **pctx,
const char *algname, ENGINE *e, int do_param,
OSSL_LIB_CTX *libctx, const char *propq);
int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey);
int do_X509_sign(X509 *x, int force_v1, EVP_PKEY *pkey, const char *md,
STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx);
int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts);
int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
STACK_OF(OPENSSL_STRING) *sigopts);
int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
STACK_OF(OPENSSL_STRING) *vfyopts);
int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
STACK_OF(OPENSSL_STRING) *sigopts);
extern char *psk_key;
unsigned char *next_protos_parse(size_t *outlen, const char *in);
int check_cert_attributes(BIO *bio, X509 *x,
const char *checkhost, const char *checkemail,
const char *checkip, int print);
void store_setup_crl_download(X509_STORE *st);
typedef struct app_http_tls_info_st {
const char *server;
const char *port;
int use_proxy;
long timeout;
SSL_CTX *ssl_ctx;
} APP_HTTP_TLS_INFO;
BIO *app_http_tls_cb(BIO *hbio, /* APP_HTTP_TLS_INFO */ void *arg,
int connect, int detail);
void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info);
# ifndef OPENSSL_NO_SOCK
ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
const char *no_proxy, SSL_CTX *ssl_ctx,
const STACK_OF(CONF_VALUE) *headers,
long timeout, const char *expected_content_type,
const ASN1_ITEM *it);
ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
const char *path, const char *proxy,
const char *no_proxy, SSL_CTX *ctx,
const STACK_OF(CONF_VALUE) *headers,
const char *content_type,
ASN1_VALUE *req, const ASN1_ITEM *req_it,
const char *expected_content_type,
long timeout, const ASN1_ITEM *rsp_it);
# endif
# define EXT_COPY_NONE 0
# define EXT_COPY_ADD 1
# define EXT_COPY_ALL 2
# define NETSCAPE_CERT_HDR "certificate"
# define APP_PASS_LEN 1024
/*
* IETF RFC 5280 says serial number must be <= 20 bytes. Use 159 bits
* so that the first bit will never be one, so that the DER encoding
* rules won't force a leading octet.
*/
# define SERIAL_RAND_BITS 159
int app_isdir(const char *);
int app_access(const char *, int flag);
int fileno_stdin(void);
int fileno_stdout(void);
int raw_read_stdin(void *, int);
int raw_write_stdout(const void *, int);
# define TM_START 0
# define TM_STOP 1
double app_tminterval(int stop, int usertime);
void make_uppercase(char *string);
typedef struct verify_options_st {
int depth;
int quiet;
int error;
int return_error;
} VERIFY_CB_ARGS;
extern VERIFY_CB_ARGS verify_args;
OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
const OSSL_PARAM *paramdefs);
void app_params_free(OSSL_PARAM *params);
int app_provider_load(OSSL_LIB_CTX *libctx, const char *provider_name);
void app_providers_cleanup(void);
EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose);
EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg);
#endif
| 14,425 | 39.63662 | 80 |
h
|
openssl
|
openssl-master/apps/include/apps_ui.h
|
/*
* Copyright 2018-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_UI_H
# define OSSL_APPS_UI_H
# define PW_MIN_LENGTH 4
typedef struct pw_cb_data {
const void *password;
const char *prompt_info;
} PW_CB_DATA;
int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_data);
int setup_ui_method(void);
void destroy_ui_method(void);
int set_base_ui_method(const UI_METHOD *ui_method);
const UI_METHOD *get_ui_method(void);
extern BIO *bio_err;
#endif
| 766 | 24.566667 | 78 |
h
|
openssl
|
openssl-master/apps/include/cmp_mock_srv.h
|
/*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Siemens AG 2018-2020
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_CMP_MOCK_SRV_H
# define OSSL_APPS_CMP_MOCK_SRV_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CMP
# include <openssl/cmp.h>
OSSL_CMP_SRV_CTX *ossl_cmp_mock_srv_new(OSSL_LIB_CTX *libctx,
const char *propq);
void ossl_cmp_mock_srv_free(OSSL_CMP_SRV_CTX *srv_ctx);
int ossl_cmp_mock_srv_set1_refCert(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert);
int ossl_cmp_mock_srv_set1_certOut(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert);
int ossl_cmp_mock_srv_set1_chainOut(OSSL_CMP_SRV_CTX *srv_ctx,
STACK_OF(X509) *chain);
int ossl_cmp_mock_srv_set1_caPubsOut(OSSL_CMP_SRV_CTX *srv_ctx,
STACK_OF(X509) *caPubs);
int ossl_cmp_mock_srv_set1_newWithNew(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert);
int ossl_cmp_mock_srv_set1_newWithOld(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert);
int ossl_cmp_mock_srv_set1_oldWithNew(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert);
int ossl_cmp_mock_srv_set_statusInfo(OSSL_CMP_SRV_CTX *srv_ctx, int status,
int fail_info, const char *text);
int ossl_cmp_mock_srv_set_sendError(OSSL_CMP_SRV_CTX *srv_ctx, int bodytype);
int ossl_cmp_mock_srv_set_pollCount(OSSL_CMP_SRV_CTX *srv_ctx, int count);
int ossl_cmp_mock_srv_set_checkAfterTime(OSSL_CMP_SRV_CTX *srv_ctx, int sec);
# endif /* !defined(OPENSSL_NO_CMP) */
#endif /* !defined(OSSL_APPS_CMP_MOCK_SRV_H) */
| 1,804 | 44.125 | 77 |
h
|
openssl
|
openssl-master/apps/include/ec_common.h
|
/*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OPENSSL_NO_EC
static const char *point_format_options[] = {
"uncompressed",
"compressed",
"hybrid",
NULL
};
static const char *asn1_encoding_options[] = {
"named_curve",
"explicit",
NULL
};
#endif
| 571 | 22.833333 | 74 |
h
|
openssl
|
openssl-master/apps/include/engine_loader.h
|
/*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ENGINE_LOADER_H
# define HEADER_ENGINE_LOADER_H
# include <openssl/store.h>
/* this is a private URI scheme */
# define ENGINE_SCHEME "org.openssl.engine"
# define ENGINE_SCHEME_COLON ENGINE_SCHEME ":"
int setup_engine_loader(void);
void destroy_engine_loader(void);
#endif
| 641 | 28.181818 | 74 |
h
|
openssl
|
openssl-master/apps/include/fmt.h
|
/*
* Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Options are shared by apps (see apps.h) and the test system
* (see test/testutil.h').
* In order to remove the dependency between apps and options, the following
* shared fields have been moved into this file.
*/
#ifndef OSSL_APPS_FMT_H
#define OSSL_APPS_FMT_H
/*
* On some platforms, it's important to distinguish between text and binary
* files. On some, there might even be specific file formats for different
* contents. The FORMAT_xxx macros are meant to express an intent with the
* file being read or created.
*/
# define B_FORMAT_TEXT 0x8000
# define FORMAT_UNDEF 0
# define FORMAT_TEXT (1 | B_FORMAT_TEXT) /* Generic text */
# define FORMAT_BINARY 2 /* Generic binary */
# define FORMAT_BASE64 (3 | B_FORMAT_TEXT) /* Base64 */
# define FORMAT_ASN1 4 /* ASN.1/DER */
# define FORMAT_PEM (5 | B_FORMAT_TEXT)
# define FORMAT_PKCS12 6
# define FORMAT_SMIME (7 | B_FORMAT_TEXT)
# define FORMAT_ENGINE 8 /* Not really a file format */
# define FORMAT_PEMRSA (9 | B_FORMAT_TEXT) /* PEM RSAPublicKey format */
# define FORMAT_ASN1RSA 10 /* DER RSAPublicKey format */
# define FORMAT_MSBLOB 11 /* MS Key blob format */
# define FORMAT_PVK 12 /* MS PVK file format */
# define FORMAT_HTTP 13 /* Download using HTTP */
# define FORMAT_NSS 14 /* NSS keylog format */
int FMT_istext(int format);
#endif /* OSSL_APPS_FMT_H_ */
| 1,898 | 40.282609 | 78 |
h
|
openssl
|
openssl-master/apps/include/function.h
|
/*
* Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_FUNCTION_H
# define OSSL_APPS_FUNCTION_H
# include <openssl/lhash.h>
# include "opt.h"
#define DEPRECATED_NO_ALTERNATIVE "unknown"
typedef enum FUNC_TYPE {
FT_none, FT_general, FT_md, FT_cipher, FT_pkey,
FT_md_alg, FT_cipher_alg
} FUNC_TYPE;
typedef struct function_st {
FUNC_TYPE type;
const char *name;
int (*func)(int argc, char *argv[]);
const OPTIONS *help;
const char *deprecated_alternative;
const char *deprecated_version;
} FUNCTION;
DEFINE_LHASH_OF_EX(FUNCTION);
/* Structure to hold the number of columns to be displayed and the
* field width used to display them.
*/
typedef struct {
int columns;
int width;
} DISPLAY_COLUMNS;
void calculate_columns(FUNCTION *functions, DISPLAY_COLUMNS *dc);
#endif
| 1,119 | 23.888889 | 74 |
h
|
openssl
|
openssl-master/apps/include/http_server.h
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_HTTP_SERVER_H
# define OSSL_HTTP_SERVER_H
# include "apps.h"
# include "log.h"
# ifndef HAVE_FORK
# if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
# define HAVE_FORK 0
# else
# define HAVE_FORK 1
# endif
# endif
# if HAVE_FORK
# undef NO_FORK
# else
# define NO_FORK
# endif
# if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
&& !defined(OPENSSL_NO_POSIX_IO)
# define HTTP_DAEMON
# include <sys/types.h>
# include <sys/wait.h>
# include <signal.h>
# define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
# endif
# ifndef OPENSSL_NO_SOCK
/*-
* Initialize an HTTP server, setting up its listening BIO
* prog: the name of the current app
* port: the port to listen on
* verbosity: the level of verbosity to use, or -1 for default: LOG_INFO
* returns a BIO for accepting requests, NULL on error
*/
BIO *http_server_init(const char *prog, const char *port, int verbosity);
/*-
* Accept an ASN.1-formatted HTTP request
* it: the expected request ASN.1 type
* preq: pointer to variable where to place the parsed request
* ppath: pointer to variable where to place the request path, or NULL
* pcbio: pointer to variable where to place the BIO for sending the response to
* acbio: the listening bio (typically as returned by http_server_init_bio())
* found_keep_alive: for returning flag if client requests persistent connection
* prog: the name of the current app, for diagnostics only
* accept_get: whether to accept GET requests (in addition to POST requests)
* timeout: connection timeout (in seconds), or 0 for none/infinite
* returns 0 in case caller should retry, then *preq == *ppath == *pcbio == NULL
* returns -1 on fatal error; also then holds *preq == *ppath == *pcbio == NULL
* returns 1 otherwise. In this case it is guaranteed that *pcbio != NULL while
* *ppath == NULL and *preq == NULL if and only if the request is invalid,
* On return value 1 the caller is responsible for sending an HTTP response,
* using http_server_send_asn1_resp() or http_server_send_status().
* The caller must free any non-NULL *preq, *ppath, and *pcbio pointers.
*/
int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
char **ppath, BIO **pcbio, BIO *acbio,
int *found_keep_alive,
const char *prog, int accept_get, int timeout);
/*-
* Send an ASN.1-formatted HTTP response
* prog: the name of the current app, for diagnostics only
* cbio: destination BIO (typically as returned by http_server_get_asn1_req())
* note: cbio should not do an encoding that changes the output length
* keep_alive: grant persistent connection
* content_type: string identifying the type of the response
* it: the response ASN.1 type
* resp: the response to send
* returns 1 on success, 0 on failure
*/
int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive,
const char *content_type,
const ASN1_ITEM *it, const ASN1_VALUE *resp);
/*-
* Send a trivial HTTP response, typically to report an error or OK
* prog: the name of the current app, for diagnostics only
* cbio: destination BIO (typically as returned by http_server_get_asn1_req())
* status: the status code to send
* reason: the corresponding human-readable string
* returns 1 on success, 0 on failure
*/
int http_server_send_status(const char *prog, BIO *cbio,
int status, const char *reason);
# endif
# ifdef HTTP_DAEMON
extern int n_responders;
extern int acfd;
void socket_timeout(int signum);
void spawn_loop(const char *prog);
# endif
#endif
| 4,043 | 35.763636 | 80 |
h
|
openssl
|
openssl-master/apps/include/log.h
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_LOG_H
# define OSSL_APPS_LOG_H
# include <openssl/bio.h>
# if !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS) \
&& !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_POSIX_IO)
# include <syslog.h>
# else
# define LOG_EMERG 0
# define LOG_ALERT 1
# define LOG_CRIT 2
# define LOG_ERR 3
# define LOG_WARNING 4
# define LOG_NOTICE 5
# define LOG_INFO 6
# define LOG_DEBUG 7
# endif
# undef LOG_TRACE
# define LOG_TRACE (LOG_DEBUG + 1)
int log_set_verbosity(const char *prog, int level);
int log_get_verbosity(void);
/*-
* Output a message using the trace API with the given category
* if the category is >= 0 and tracing is enabled.
* Log the message to syslog if multi-threaded HTTP_DAEMON, else to bio_err
* if the verbosity is sufficient for the given level of severity.
* Yet cannot do both types of output in strict ANSI mode.
* category: trace category as defined in trace.h, or -1
* prog: the name of the current app, or NULL
* level: the severity of the message, e.g., LOG_ERR
* fmt: message format, which should not include a trailing newline
* ...: potential extra parameters like with printf()
* returns nothing
*/
void trace_log_message(int category,
const char *prog, int level, const char *fmt, ...);
#endif /* OSSL_APPS_LOG_H */
| 1,675 | 31.862745 | 75 |
h
|
openssl
|
openssl-master/apps/include/names.h
|
/*
* Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/safestack.h>
/* Standard comparing function for names */
int name_cmp(const char * const *a, const char * const *b);
/* collect_names is meant to be used with EVP_{type}_doall_names */
void collect_names(const char *name, void *vdata);
/* Sorts and prints a stack of names to |out| */
void print_names(BIO *out, STACK_OF(OPENSSL_CSTRING) *names);
| 698 | 37.833333 | 74 |
h
|
openssl
|
openssl-master/apps/include/opt.h
|
/*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_OPT_H
#define OSSL_APPS_OPT_H
#include <sys/types.h>
#include <openssl/e_os2.h>
#include <openssl/types.h>
#include <stdarg.h>
#define OPT_COMMON OPT_ERR = -1, OPT_EOF = 0, OPT_HELP
/*
* Common verification options.
*/
# define OPT_V_ENUM \
OPT_V__FIRST=2000, \
OPT_V_POLICY, OPT_V_PURPOSE, OPT_V_VERIFY_NAME, OPT_V_VERIFY_DEPTH, \
OPT_V_ATTIME, OPT_V_VERIFY_HOSTNAME, OPT_V_VERIFY_EMAIL, \
OPT_V_VERIFY_IP, OPT_V_IGNORE_CRITICAL, OPT_V_ISSUER_CHECKS, \
OPT_V_CRL_CHECK, OPT_V_CRL_CHECK_ALL, OPT_V_POLICY_CHECK, \
OPT_V_EXPLICIT_POLICY, OPT_V_INHIBIT_ANY, OPT_V_INHIBIT_MAP, \
OPT_V_X509_STRICT, OPT_V_EXTENDED_CRL, OPT_V_USE_DELTAS, \
OPT_V_POLICY_PRINT, OPT_V_CHECK_SS_SIG, OPT_V_TRUSTED_FIRST, \
OPT_V_SUITEB_128_ONLY, OPT_V_SUITEB_128, OPT_V_SUITEB_192, \
OPT_V_PARTIAL_CHAIN, OPT_V_NO_ALT_CHAINS, OPT_V_NO_CHECK_TIME, \
OPT_V_VERIFY_AUTH_LEVEL, OPT_V_ALLOW_PROXY_CERTS, \
OPT_V__LAST
# define OPT_V_OPTIONS \
OPT_SECTION("Validation"), \
{ "policy", OPT_V_POLICY, 's', "adds policy to the acceptable policy set"}, \
{ "purpose", OPT_V_PURPOSE, 's', \
"certificate chain purpose"}, \
{ "verify_name", OPT_V_VERIFY_NAME, 's', "verification policy name"}, \
{ "verify_depth", OPT_V_VERIFY_DEPTH, 'n', \
"chain depth limit" }, \
{ "auth_level", OPT_V_VERIFY_AUTH_LEVEL, 'n', \
"chain authentication security level" }, \
{ "attime", OPT_V_ATTIME, 'M', "verification epoch time" }, \
{ "verify_hostname", OPT_V_VERIFY_HOSTNAME, 's', \
"expected peer hostname" }, \
{ "verify_email", OPT_V_VERIFY_EMAIL, 's', \
"expected peer email" }, \
{ "verify_ip", OPT_V_VERIFY_IP, 's', \
"expected peer IP address" }, \
{ "ignore_critical", OPT_V_IGNORE_CRITICAL, '-', \
"permit unhandled critical extensions"}, \
{ "issuer_checks", OPT_V_ISSUER_CHECKS, '-', "(deprecated)"}, \
{ "crl_check", OPT_V_CRL_CHECK, '-', "check leaf certificate revocation" }, \
{ "crl_check_all", OPT_V_CRL_CHECK_ALL, '-', "check full chain revocation" }, \
{ "policy_check", OPT_V_POLICY_CHECK, '-', "perform rfc5280 policy checks"}, \
{ "explicit_policy", OPT_V_EXPLICIT_POLICY, '-', \
"set policy variable require-explicit-policy"}, \
{ "inhibit_any", OPT_V_INHIBIT_ANY, '-', \
"set policy variable inhibit-any-policy"}, \
{ "inhibit_map", OPT_V_INHIBIT_MAP, '-', \
"set policy variable inhibit-policy-mapping"}, \
{ "x509_strict", OPT_V_X509_STRICT, '-', \
"disable certificate compatibility work-arounds"}, \
{ "extended_crl", OPT_V_EXTENDED_CRL, '-', \
"enable extended CRL features"}, \
{ "use_deltas", OPT_V_USE_DELTAS, '-', \
"use delta CRLs"}, \
{ "policy_print", OPT_V_POLICY_PRINT, '-', \
"print policy processing diagnostics"}, \
{ "check_ss_sig", OPT_V_CHECK_SS_SIG, '-', \
"check root CA self-signatures"}, \
{ "trusted_first", OPT_V_TRUSTED_FIRST, '-', \
"search trust store first (default)" }, \
{ "suiteB_128_only", OPT_V_SUITEB_128_ONLY, '-', "Suite B 128-bit-only mode"}, \
{ "suiteB_128", OPT_V_SUITEB_128, '-', \
"Suite B 128-bit mode allowing 192-bit algorithms"}, \
{ "suiteB_192", OPT_V_SUITEB_192, '-', "Suite B 192-bit-only mode" }, \
{ "partial_chain", OPT_V_PARTIAL_CHAIN, '-', \
"accept chains anchored by intermediate trust-store CAs"}, \
{ "no_alt_chains", OPT_V_NO_ALT_CHAINS, '-', "(deprecated)" }, \
{ "no_check_time", OPT_V_NO_CHECK_TIME, '-', "ignore certificate validity time" }, \
{ "allow_proxy_certs", OPT_V_ALLOW_PROXY_CERTS, '-', "allow the use of proxy certificates" }
# define OPT_V_CASES \
OPT_V__FIRST: case OPT_V__LAST: break; \
case OPT_V_POLICY: \
case OPT_V_PURPOSE: \
case OPT_V_VERIFY_NAME: \
case OPT_V_VERIFY_DEPTH: \
case OPT_V_VERIFY_AUTH_LEVEL: \
case OPT_V_ATTIME: \
case OPT_V_VERIFY_HOSTNAME: \
case OPT_V_VERIFY_EMAIL: \
case OPT_V_VERIFY_IP: \
case OPT_V_IGNORE_CRITICAL: \
case OPT_V_ISSUER_CHECKS: \
case OPT_V_CRL_CHECK: \
case OPT_V_CRL_CHECK_ALL: \
case OPT_V_POLICY_CHECK: \
case OPT_V_EXPLICIT_POLICY: \
case OPT_V_INHIBIT_ANY: \
case OPT_V_INHIBIT_MAP: \
case OPT_V_X509_STRICT: \
case OPT_V_EXTENDED_CRL: \
case OPT_V_USE_DELTAS: \
case OPT_V_POLICY_PRINT: \
case OPT_V_CHECK_SS_SIG: \
case OPT_V_TRUSTED_FIRST: \
case OPT_V_SUITEB_128_ONLY: \
case OPT_V_SUITEB_128: \
case OPT_V_SUITEB_192: \
case OPT_V_PARTIAL_CHAIN: \
case OPT_V_NO_ALT_CHAINS: \
case OPT_V_NO_CHECK_TIME: \
case OPT_V_ALLOW_PROXY_CERTS
/*
* Common "extended validation" options.
*/
# define OPT_X_ENUM \
OPT_X__FIRST=1000, \
OPT_X_KEY, OPT_X_CERT, OPT_X_CHAIN, OPT_X_CHAIN_BUILD, \
OPT_X_CERTFORM, OPT_X_KEYFORM, \
OPT_X__LAST
# define OPT_X_OPTIONS \
OPT_SECTION("Extended certificate"), \
{ "xkey", OPT_X_KEY, '<', "key for Extended certificates"}, \
{ "xcert", OPT_X_CERT, '<', "cert for Extended certificates"}, \
{ "xchain", OPT_X_CHAIN, '<', "chain for Extended certificates"}, \
{ "xchain_build", OPT_X_CHAIN_BUILD, '-', \
"build certificate chain for the extended certificates"}, \
{ "xcertform", OPT_X_CERTFORM, 'F', \
"format of Extended certificate (PEM/DER/P12); has no effect" }, \
{ "xkeyform", OPT_X_KEYFORM, 'F', \
"format of Extended certificate's key (DER/PEM/P12); has no effect"}
# define OPT_X_CASES \
OPT_X__FIRST: case OPT_X__LAST: break; \
case OPT_X_KEY: \
case OPT_X_CERT: \
case OPT_X_CHAIN: \
case OPT_X_CHAIN_BUILD: \
case OPT_X_CERTFORM: \
case OPT_X_KEYFORM
/*
* Common SSL options.
* Any changes here must be coordinated with ../ssl/ssl_conf.c
*/
# define OPT_S_ENUM \
OPT_S__FIRST=3000, \
OPT_S_NOSSL3, OPT_S_NOTLS1, OPT_S_NOTLS1_1, OPT_S_NOTLS1_2, \
OPT_S_NOTLS1_3, OPT_S_BUGS, OPT_S_NO_COMP, OPT_S_NOTICKET, \
OPT_S_SERVERPREF, OPT_S_LEGACYRENEG, OPT_S_CLIENTRENEG, \
OPT_S_LEGACYCONN, \
OPT_S_ONRESUMP, OPT_S_NOLEGACYCONN, OPT_S_ALLOW_NO_DHE_KEX, \
OPT_S_PRIORITIZE_CHACHA, \
OPT_S_STRICT, OPT_S_SIGALGS, OPT_S_CLIENTSIGALGS, OPT_S_GROUPS, \
OPT_S_CURVES, OPT_S_NAMEDCURVE, OPT_S_CIPHER, OPT_S_CIPHERSUITES, \
OPT_S_RECORD_PADDING, OPT_S_DEBUGBROKE, OPT_S_COMP, \
OPT_S_MINPROTO, OPT_S_MAXPROTO, \
OPT_S_NO_RENEGOTIATION, OPT_S_NO_MIDDLEBOX, OPT_S_NO_ETM, \
OPT_S_NO_EMS, \
OPT_S_NO_TX_CERT_COMP, \
OPT_S_NO_RX_CERT_COMP, \
OPT_S__LAST
# define OPT_S_OPTIONS \
OPT_SECTION("TLS/SSL"), \
{"no_ssl3", OPT_S_NOSSL3, '-',"Just disable SSLv3" }, \
{"no_tls1", OPT_S_NOTLS1, '-', "Just disable TLSv1"}, \
{"no_tls1_1", OPT_S_NOTLS1_1, '-', "Just disable TLSv1.1" }, \
{"no_tls1_2", OPT_S_NOTLS1_2, '-', "Just disable TLSv1.2"}, \
{"no_tls1_3", OPT_S_NOTLS1_3, '-', "Just disable TLSv1.3"}, \
{"bugs", OPT_S_BUGS, '-', "Turn on SSL bug compatibility"}, \
{"no_comp", OPT_S_NO_COMP, '-', "Disable SSL/TLS compression (default)" }, \
{"comp", OPT_S_COMP, '-', "Use SSL/TLS-level compression" }, \
{"no_tx_cert_comp", OPT_S_NO_TX_CERT_COMP, '-', "Disable sending TLSv1.3 compressed certificates" }, \
{"no_rx_cert_comp", OPT_S_NO_RX_CERT_COMP, '-', "Disable receiving TLSv1.3 compressed certificates" }, \
{"no_ticket", OPT_S_NOTICKET, '-', \
"Disable use of TLS session tickets"}, \
{"serverpref", OPT_S_SERVERPREF, '-', "Use server's cipher preferences"}, \
{"legacy_renegotiation", OPT_S_LEGACYRENEG, '-', \
"Enable use of legacy renegotiation (dangerous)"}, \
{"client_renegotiation", OPT_S_CLIENTRENEG, '-', \
"Allow client-initiated renegotiation" }, \
{"no_renegotiation", OPT_S_NO_RENEGOTIATION, '-', \
"Disable all renegotiation."}, \
{"legacy_server_connect", OPT_S_LEGACYCONN, '-', \
"Allow initial connection to servers that don't support RI"}, \
{"no_resumption_on_reneg", OPT_S_ONRESUMP, '-', \
"Disallow session resumption on renegotiation"}, \
{"no_legacy_server_connect", OPT_S_NOLEGACYCONN, '-', \
"Disallow initial connection to servers that don't support RI"}, \
{"allow_no_dhe_kex", OPT_S_ALLOW_NO_DHE_KEX, '-', \
"In TLSv1.3 allow non-(ec)dhe based key exchange on resumption"}, \
{"prioritize_chacha", OPT_S_PRIORITIZE_CHACHA, '-', \
"Prioritize ChaCha ciphers when preferred by clients"}, \
{"strict", OPT_S_STRICT, '-', \
"Enforce strict certificate checks as per TLS standard"}, \
{"sigalgs", OPT_S_SIGALGS, 's', \
"Signature algorithms to support (colon-separated list)" }, \
{"client_sigalgs", OPT_S_CLIENTSIGALGS, 's', \
"Signature algorithms to support for client certificate" \
" authentication (colon-separated list)" }, \
{"groups", OPT_S_GROUPS, 's', \
"Groups to advertise (colon-separated list)" }, \
{"curves", OPT_S_CURVES, 's', \
"Groups to advertise (colon-separated list)" }, \
{"named_curve", OPT_S_NAMEDCURVE, 's', \
"Elliptic curve used for ECDHE (server-side only)" }, \
{"cipher", OPT_S_CIPHER, 's', "Specify TLSv1.2 and below cipher list to be used"}, \
{"ciphersuites", OPT_S_CIPHERSUITES, 's', "Specify TLSv1.3 ciphersuites to be used"}, \
{"min_protocol", OPT_S_MINPROTO, 's', "Specify the minimum protocol version to be used"}, \
{"max_protocol", OPT_S_MAXPROTO, 's', "Specify the maximum protocol version to be used"}, \
{"record_padding", OPT_S_RECORD_PADDING, 's', \
"Block size to pad TLS 1.3 records to."}, \
{"debug_broken_protocol", OPT_S_DEBUGBROKE, '-', \
"Perform all sorts of protocol violations for testing purposes"}, \
{"no_middlebox", OPT_S_NO_MIDDLEBOX, '-', \
"Disable TLSv1.3 middlebox compat mode" }, \
{"no_etm", OPT_S_NO_ETM, '-', \
"Disable Encrypt-then-Mac extension"}, \
{"no_ems", OPT_S_NO_EMS, '-', \
"Disable Extended master secret extension"}
# define OPT_S_CASES \
OPT_S__FIRST: case OPT_S__LAST: break; \
case OPT_S_NOSSL3: \
case OPT_S_NOTLS1: \
case OPT_S_NOTLS1_1: \
case OPT_S_NOTLS1_2: \
case OPT_S_NOTLS1_3: \
case OPT_S_BUGS: \
case OPT_S_NO_COMP: \
case OPT_S_COMP: \
case OPT_S_NO_TX_CERT_COMP: \
case OPT_S_NO_RX_CERT_COMP: \
case OPT_S_NOTICKET: \
case OPT_S_SERVERPREF: \
case OPT_S_LEGACYRENEG: \
case OPT_S_CLIENTRENEG: \
case OPT_S_LEGACYCONN: \
case OPT_S_ONRESUMP: \
case OPT_S_NOLEGACYCONN: \
case OPT_S_ALLOW_NO_DHE_KEX: \
case OPT_S_PRIORITIZE_CHACHA: \
case OPT_S_STRICT: \
case OPT_S_SIGALGS: \
case OPT_S_CLIENTSIGALGS: \
case OPT_S_GROUPS: \
case OPT_S_CURVES: \
case OPT_S_NAMEDCURVE: \
case OPT_S_CIPHER: \
case OPT_S_CIPHERSUITES: \
case OPT_S_RECORD_PADDING: \
case OPT_S_NO_RENEGOTIATION: \
case OPT_S_MINPROTO: \
case OPT_S_MAXPROTO: \
case OPT_S_DEBUGBROKE: \
case OPT_S_NO_MIDDLEBOX: \
case OPT_S_NO_ETM: \
case OPT_S_NO_EMS
#define IS_NO_PROT_FLAG(o) \
(o == OPT_S_NOSSL3 || o == OPT_S_NOTLS1 || o == OPT_S_NOTLS1_1 \
|| o == OPT_S_NOTLS1_2 || o == OPT_S_NOTLS1_3)
/*
* Random state options.
*/
# define OPT_R_ENUM \
OPT_R__FIRST=1500, OPT_R_RAND, OPT_R_WRITERAND, OPT_R__LAST
# define OPT_R_OPTIONS \
OPT_SECTION("Random state"), \
{"rand", OPT_R_RAND, 's', "Load the given file(s) into the random number generator"}, \
{"writerand", OPT_R_WRITERAND, '>', "Write random data to the specified file"}
# define OPT_R_CASES \
OPT_R__FIRST: case OPT_R__LAST: break; \
case OPT_R_RAND: case OPT_R_WRITERAND
/*
* Provider options.
*/
# define OPT_PROV_ENUM \
OPT_PROV__FIRST=1600, \
OPT_PROV_PROVIDER, OPT_PROV_PROVIDER_PATH, OPT_PROV_PROPQUERY, \
OPT_PROV__LAST
# define OPT_CONFIG_OPTION \
{ "config", OPT_CONFIG, '<', "Load a configuration file (this may load modules)" }
# define OPT_PROV_OPTIONS \
OPT_SECTION("Provider"), \
{ "provider-path", OPT_PROV_PROVIDER_PATH, 's', "Provider load path (must be before 'provider' argument if required)" }, \
{ "provider", OPT_PROV_PROVIDER, 's', "Provider to load (can be specified multiple times)" }, \
{ "propquery", OPT_PROV_PROPQUERY, 's', "Property query used when fetching algorithms" }
# define OPT_PROV_CASES \
OPT_PROV__FIRST: case OPT_PROV__LAST: break; \
case OPT_PROV_PROVIDER: \
case OPT_PROV_PROVIDER_PATH: \
case OPT_PROV_PROPQUERY
/*
* Option parsing.
*/
extern const char OPT_HELP_STR[];
extern const char OPT_MORE_STR[];
extern const char OPT_SECTION_STR[];
extern const char OPT_PARAM_STR[];
typedef struct options_st {
const char *name;
int retval;
/*-
* value type:
*
* '-' no value (also the value zero)
* 'n' number (type 'int')
* 'p' positive number (type 'int')
* 'u' unsigned number (type 'unsigned long')
* 'l' number (type 'unsigned long')
* 'M' number (type 'intmax_t')
* 'U' unsigned number (type 'uintmax_t')
* 's' string
* '<' input file
* '>' output file
* '/' directory
* 'f' any format [OPT_FMT_ANY]
* 'F' der/pem format [OPT_FMT_PEMDER]
* 'A' any ASN1, der/pem/b64 format [OPT_FMT_ASN1]
* 'E' der/pem/engine format [OPT_FMT_PDE]
* 'c' pem/der/smime format [OPT_FMT_PDS]
*
* The 'l', 'n' and 'u' value types include the values zero,
* the 'p' value type does not.
*/
int valtype;
const char *helpstr;
} OPTIONS;
/* Special retval values: */
#define OPT_PARAM 0 /* same as OPT_EOF usually defined in apps */
#define OPT_DUP -2 /* marks duplicate occurrence of option in help output */
/*
* A string/int pairing; widely use for option value lookup, hence the
* name OPT_PAIR. But that name is misleading in s_cb.c, so we also use
* the "generic" name STRINT_PAIR.
*/
typedef struct string_int_pair_st {
const char *name;
int retval;
} OPT_PAIR, STRINT_PAIR;
/* Flags to pass into opt_format; see FORMAT_xxx, below. */
# define OPT_FMT_PEM (1L << 1)
# define OPT_FMT_DER (1L << 2)
# define OPT_FMT_B64 (1L << 3)
# define OPT_FMT_PKCS12 (1L << 4)
# define OPT_FMT_SMIME (1L << 5)
# define OPT_FMT_ENGINE (1L << 6)
# define OPT_FMT_MSBLOB (1L << 7)
# define OPT_FMT_NSS (1L << 8)
# define OPT_FMT_TEXT (1L << 9)
# define OPT_FMT_HTTP (1L << 10)
# define OPT_FMT_PVK (1L << 11)
# define OPT_FMT_PEMDER (OPT_FMT_PEM | OPT_FMT_DER)
# define OPT_FMT_ASN1 (OPT_FMT_PEM | OPT_FMT_DER | OPT_FMT_B64)
# define OPT_FMT_PDE (OPT_FMT_PEMDER | OPT_FMT_ENGINE)
# define OPT_FMT_PDS (OPT_FMT_PEMDER | OPT_FMT_SMIME)
# define OPT_FMT_ANY ( \
OPT_FMT_PEM | OPT_FMT_DER | OPT_FMT_B64 | \
OPT_FMT_PKCS12 | OPT_FMT_SMIME | \
OPT_FMT_ENGINE | OPT_FMT_MSBLOB | OPT_FMT_NSS | \
OPT_FMT_TEXT | OPT_FMT_HTTP | OPT_FMT_PVK)
/* Divide options into sections when displaying usage */
#define OPT_SECTION(sec) { OPT_SECTION_STR, 1, '-', sec " options:\n" }
#define OPT_PARAMETERS() { OPT_PARAM_STR, 1, '-', "Parameters:\n" }
const char *opt_path_end(const char *filename);
char *opt_init(int ac, char **av, const OPTIONS * o);
char *opt_progname(const char *argv0);
char *opt_appname(const char *argv0);
char *opt_getprog(void);
void opt_help(const OPTIONS * list);
void opt_begin(void);
int opt_next(void);
char *opt_flag(void);
char *opt_arg(void);
char *opt_unknown(void);
void reset_unknown(void);
int opt_cipher(const char *name, EVP_CIPHER **cipherp);
int opt_cipher_any(const char *name, EVP_CIPHER **cipherp);
int opt_cipher_silent(const char *name, EVP_CIPHER **cipherp);
int opt_check_md(const char *name);
int opt_md(const char *name, EVP_MD **mdp);
int opt_md_silent(const char *name, EVP_MD **mdp);
int opt_int(const char *arg, int *result);
void opt_set_unknown_name(const char *name);
int opt_int_arg(void);
int opt_long(const char *arg, long *result);
int opt_ulong(const char *arg, unsigned long *result);
int opt_intmax(const char *arg, ossl_intmax_t *result);
int opt_uintmax(const char *arg, ossl_uintmax_t *result);
int opt_isdir(const char *name);
int opt_format(const char *s, unsigned long flags, int *result);
void print_format_error(int format, unsigned long flags);
int opt_printf_stderr(const char *fmt, ...);
int opt_string(const char *name, const char **options);
int opt_pair(const char *arg, const OPT_PAIR * pairs, int *result);
int opt_verify(int i, X509_VERIFY_PARAM *vpm);
int opt_rand(int i);
int opt_provider(int i);
int opt_provider_option_given(void);
char **opt_rest(void);
int opt_num_rest(void);
int opt_check_rest_arg(const char *expected);
/* Returns non-zero if legacy paths are still available */
int opt_legacy_okay(void);
#endif /* OSSL_APPS_OPT_H */
| 18,390 | 40.988584 | 130 |
h
|
openssl
|
openssl-master/apps/include/platform.h
|
/*
* Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_PLATFORM_H
# define OSSL_APPS_PLATFORM_H
# include <openssl/e_os2.h>
# if defined(OPENSSL_SYS_VMS) && defined(__DECC)
/*
* VMS C only for now, implemented in vms_decc_init.c
* If other C compilers forget to terminate argv with NULL, this function
* can be re-used.
*/
char **copy_argv(int *argc, char *argv[]);
# endif
# ifdef _WIN32
/*
* Win32-specific argv initialization that splits OS-supplied UNICODE
* command line string to array of UTF8-encoded strings.
*/
void win32_utf8argv(int *argc, char **argv[]);
# endif
#endif
| 888 | 25.939394 | 74 |
h
|
openssl
|
openssl-master/apps/include/s_apps.h
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <openssl/ssl.h>
#include <openssl/srp.h>
#define PORT "4433"
#define PROTOCOL "tcp"
#define SSL_VERSION_ALLOWS_RENEGOTIATION(s) \
(SSL_is_dtls(s) || (SSL_version(s) < TLS1_3_VERSION))
typedef int (*do_server_cb)(int s, int stype, int prot, unsigned char *context);
void get_sock_info_address(int asock, char **hostname, char **service);
int report_server_accept(BIO *out, int asock, int with_address, int with_pid);
int do_server(int *accept_sock, const char *host, const char *port,
int family, int type, int protocol, do_server_cb cb,
unsigned char *context, int naccept, BIO *bio_s_out,
int tfo);
int verify_callback(int ok, X509_STORE_CTX *ctx);
int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file);
int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
STACK_OF(X509) *chain, int build_chain);
int ssl_print_sigalgs(BIO *out, SSL *s);
int ssl_print_point_formats(BIO *out, SSL *s);
int ssl_print_groups(BIO *out, SSL *s, int noshared);
int ssl_print_tmp_key(BIO *out, SSL *s);
int init_client(int *sock, const char *host, const char *port,
const char *bindhost, const char *bindport,
int family, int type, int protocol, int tfo, int doconn,
BIO_ADDR **ba_ret);
int should_retry(int i);
void do_ssl_shutdown(SSL *ssl);
long bio_dump_callback(BIO *bio, int cmd, const char *argp, size_t len,
int argi, long argl, int ret, size_t *processed);
void apps_ssl_info_callback(const SSL *s, int where, int ret);
void msg_cb(int write_p, int version, int content_type, const void *buf,
size_t len, SSL *ssl, void *arg);
void tlsext_cb(SSL *s, int client_server, int type, const unsigned char *data,
int len, void *arg);
int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
unsigned int *cookie_len);
int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
unsigned int cookie_len);
#ifdef __VMS /* 31 char symbol name limit */
# define generate_stateless_cookie_callback generate_stateless_cookie_cb
# define verify_stateless_cookie_callback verify_stateless_cookie_cb
#endif
int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
size_t *cookie_len);
int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
size_t cookie_len);
typedef struct ssl_excert_st SSL_EXCERT;
void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc);
void ssl_excert_free(SSL_EXCERT *exc);
int args_excert(int option, SSL_EXCERT **pexc);
int load_excert(SSL_EXCERT **pexc);
void print_verify_detail(SSL *s, BIO *bio);
void print_ssl_summary(SSL *s);
int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str, SSL_CTX *ctx);
int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls,
int crl_download);
int ssl_load_stores(SSL_CTX *ctx, const char *vfyCApath,
const char *vfyCAfile, const char *vfyCAstore,
const char *chCApath, const char *chCAfile,
const char *chCAstore, STACK_OF(X509_CRL) *crls,
int crl_download);
void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose);
int set_keylog_file(SSL_CTX *ctx, const char *keylog_file);
void print_ca_names(BIO *bio, SSL *s);
void ssl_print_secure_renegotiation_notes(BIO *bio, SSL *s);
#ifndef OPENSSL_NO_SRP
/* The client side SRP context that we pass to all SRP related callbacks */
typedef struct srp_arg_st {
char *srppassin;
char *srplogin;
int msg; /* copy from c_msg */
int debug; /* copy from c_debug */
int amp; /* allow more groups */
int strength; /* minimal size for N */
} SRP_ARG;
int set_up_srp_arg(SSL_CTX *ctx, SRP_ARG *srp_arg, int srp_lateuser, int c_msg,
int c_debug);
void set_up_dummy_srp(SSL_CTX *ctx);
/* The server side SRP context that we pass to all SRP related callbacks */
typedef struct srpsrvparm_st {
char *login;
SRP_VBASE *vb;
SRP_user_pwd *user;
} srpsrvparm;
int set_up_srp_verifier_file(SSL_CTX *ctx, srpsrvparm *srp_callback_parm,
char *srpuserseed, char *srp_verifier_file);
void lookup_srp_user(srpsrvparm *srp_callback_parm, BIO *bio_s_out);
#endif /* OPENSSL_NO_SRP */
| 4,914 | 41.73913 | 80 |
h
|
openssl
|
openssl-master/apps/include/vms_term_sock.h
|
/*
* Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2016 VMS Software, Inc. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_APPS_VMS_TERM_SOCK_H
# define OSSL_APPS_VMS_TERM_SOCK_H
/*
** Terminal Socket Function Codes
*/
# define TERM_SOCK_CREATE 1
# define TERM_SOCK_DELETE 2
/*
** Terminal Socket Status Codes
*/
# define TERM_SOCK_FAILURE 0
# define TERM_SOCK_SUCCESS 1
/*
** Terminal Socket Prototype
*/
int TerminalSocket (int FunctionCode, int *ReturnSocket);
#endif
| 777 | 23.3125 | 74 |
h
|
openssl
|
openssl-master/apps/lib/app_libctx.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "app_libctx.h"
#include "apps.h"
static OSSL_LIB_CTX *app_libctx = NULL;
static const char *app_propq = NULL;
int app_set_propq(const char *arg)
{
app_propq = arg;
return 1;
}
const char *app_get0_propq(void)
{
return app_propq;
}
OSSL_LIB_CTX *app_get0_libctx(void)
{
return app_libctx;
}
OSSL_LIB_CTX *app_create_libctx(void)
{
/*
* Load the NULL provider into the default library context and create a
* library context which will then be used for any OPT_PROV options.
*/
if (app_libctx == NULL) {
if (!app_provider_load(NULL, "null")) {
opt_printf_stderr("Failed to create null provider\n");
return NULL;
}
app_libctx = OSSL_LIB_CTX_new();
}
if (app_libctx == NULL)
opt_printf_stderr("Failed to create library context\n");
return app_libctx;
}
| 1,206 | 23.632653 | 75 |
c
|
openssl
|
openssl-master/apps/lib/app_params.c
|
/*
* Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "apps.h"
#include "app_params.h"
static int describe_param_type(char *buf, size_t bufsz, const OSSL_PARAM *param)
{
const char *type_mod = "";
const char *type = NULL;
int show_type_number = 0;
int printed_len;
switch (param->data_type) {
case OSSL_PARAM_UNSIGNED_INTEGER:
type_mod = "unsigned ";
/* FALLTHRU */
case OSSL_PARAM_INTEGER:
type = "integer";
break;
case OSSL_PARAM_UTF8_PTR:
type_mod = "pointer to a ";
/* FALLTHRU */
case OSSL_PARAM_UTF8_STRING:
type = "UTF8 encoded string";
break;
case OSSL_PARAM_OCTET_PTR:
type_mod = "pointer to an ";
/* FALLTHRU */
case OSSL_PARAM_OCTET_STRING:
type = "octet string";
break;
default:
type = "unknown type";
show_type_number = 1;
break;
}
printed_len = BIO_snprintf(buf, bufsz, "%s: ", param->key);
if (printed_len > 0) {
buf += printed_len;
bufsz -= printed_len;
}
printed_len = BIO_snprintf(buf, bufsz, "%s%s", type_mod, type);
if (printed_len > 0) {
buf += printed_len;
bufsz -= printed_len;
}
if (show_type_number) {
printed_len = BIO_snprintf(buf, bufsz, " [%d]", param->data_type);
if (printed_len > 0) {
buf += printed_len;
bufsz -= printed_len;
}
}
if (param->data_size == 0)
printed_len = BIO_snprintf(buf, bufsz, " (arbitrary size)");
else
printed_len = BIO_snprintf(buf, bufsz, " (max %zu bytes large)",
param->data_size);
if (printed_len > 0) {
buf += printed_len;
bufsz -= printed_len;
}
*buf = '\0';
return 1;
}
int print_param_types(const char *thing, const OSSL_PARAM *pdefs, int indent)
{
if (pdefs == NULL) {
return 1;
} else if (pdefs->key == NULL) {
/*
* An empty list? This shouldn't happen, but let's just make sure to
* say something if there's a badly written provider...
*/
BIO_printf(bio_out, "%*sEmpty list of %s (!!!)\n", indent, "", thing);
} else {
BIO_printf(bio_out, "%*s%s:\n", indent, "", thing);
for (; pdefs->key != NULL; pdefs++) {
char buf[200]; /* This should be ample space */
describe_param_type(buf, sizeof(buf), pdefs);
BIO_printf(bio_out, "%*s %s\n", indent, "", buf);
}
}
return 1;
}
void print_param_value(const OSSL_PARAM *p, int indent)
{
int64_t i;
uint64_t u;
printf("%*s%s: ", indent, "", p->key);
switch (p->data_type) {
case OSSL_PARAM_UNSIGNED_INTEGER:
if (OSSL_PARAM_get_uint64(p, &u))
BIO_printf(bio_out, "%llu\n", (unsigned long long int)u);
else
BIO_printf(bio_out, "error getting value\n");
break;
case OSSL_PARAM_INTEGER:
if (OSSL_PARAM_get_int64(p, &i))
BIO_printf(bio_out, "%lld\n", (long long int)i);
else
BIO_printf(bio_out, "error getting value\n");
break;
case OSSL_PARAM_UTF8_PTR:
BIO_printf(bio_out, "'%s'\n", *(char **)(p->data));
break;
case OSSL_PARAM_UTF8_STRING:
BIO_printf(bio_out, "'%s'\n", (char *)p->data);
break;
case OSSL_PARAM_OCTET_PTR:
case OSSL_PARAM_OCTET_STRING:
BIO_printf(bio_out, "<%zu bytes>\n", p->data_size);
break;
default:
BIO_printf(bio_out, "unknown type (%u) of %zu bytes\n",
p->data_type, p->data_size);
break;
}
}
| 3,959 | 28.774436 | 80 |
c
|
openssl
|
openssl-master/apps/lib/app_provider.c
|
/*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "apps.h"
#include <string.h>
#include <openssl/err.h>
#include <openssl/provider.h>
#include <openssl/safestack.h>
/* Non-zero if any of the provider options have been seen */
static int provider_option_given = 0;
DEFINE_STACK_OF(OSSL_PROVIDER)
/*
* See comments in opt_verify for explanation of this.
*/
enum prov_range { OPT_PROV_ENUM };
static STACK_OF(OSSL_PROVIDER) *app_providers = NULL;
static void provider_free(OSSL_PROVIDER *prov)
{
OSSL_PROVIDER_unload(prov);
}
int app_provider_load(OSSL_LIB_CTX *libctx, const char *provider_name)
{
OSSL_PROVIDER *prov;
prov = OSSL_PROVIDER_load(libctx, provider_name);
if (prov == NULL) {
opt_printf_stderr("%s: unable to load provider %s\n"
"Hint: use -provider-path option or OPENSSL_MODULES environment variable.\n",
opt_getprog(), provider_name);
ERR_print_errors(bio_err);
return 0;
}
if (app_providers == NULL)
app_providers = sk_OSSL_PROVIDER_new_null();
if (app_providers == NULL
|| !sk_OSSL_PROVIDER_push(app_providers, prov)) {
app_providers_cleanup();
return 0;
}
return 1;
}
void app_providers_cleanup(void)
{
sk_OSSL_PROVIDER_pop_free(app_providers, provider_free);
app_providers = NULL;
}
static int opt_provider_path(const char *path)
{
if (path != NULL && *path == '\0')
path = NULL;
return OSSL_PROVIDER_set_default_search_path(app_get0_libctx(), path);
}
int opt_provider(int opt)
{
const int given = provider_option_given;
provider_option_given = 1;
switch ((enum prov_range)opt) {
case OPT_PROV__FIRST:
case OPT_PROV__LAST:
return 1;
case OPT_PROV_PROVIDER:
return app_provider_load(app_get0_libctx(), opt_arg());
case OPT_PROV_PROVIDER_PATH:
return opt_provider_path(opt_arg());
case OPT_PROV_PROPQUERY:
return app_set_propq(opt_arg());
}
/* Should never get here but if we do, undo what we did earlier */
provider_option_given = given;
return 0;
}
int opt_provider_option_given(void)
{
return provider_option_given;
}
| 2,500 | 25.892473 | 103 |
c
|
openssl
|
openssl-master/apps/lib/app_rand.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/conf.h>
static char *save_rand_file;
static STACK_OF(OPENSSL_STRING) *randfiles;
void app_RAND_load_conf(CONF *c, const char *section)
{
const char *randfile = app_conf_try_string(c, section, "RANDFILE");
if (randfile == NULL)
return;
if (RAND_load_file(randfile, -1) < 0) {
BIO_printf(bio_err, "Can't load %s into RNG\n", randfile);
ERR_print_errors(bio_err);
}
if (save_rand_file == NULL) {
save_rand_file = OPENSSL_strdup(randfile);
/* If some internal memory errors have occurred */
if (save_rand_file == NULL) {
BIO_printf(bio_err, "Can't duplicate %s\n", randfile);
ERR_print_errors(bio_err);
}
}
}
static int loadfiles(char *name)
{
char *p;
int last, ret = 1;
for (;;) {
last = 0;
for (p = name; *p != '\0' && *p != LIST_SEPARATOR_CHAR; p++)
continue;
if (*p == '\0')
last = 1;
*p = '\0';
if (RAND_load_file(name, -1) < 0) {
BIO_printf(bio_err, "Can't load %s into RNG\n", name);
ERR_print_errors(bio_err);
ret = 0;
}
if (last)
break;
name = p + 1;
if (*name == '\0')
break;
}
return ret;
}
int app_RAND_load(void)
{
char *p;
int i, ret = 1;
for (i = 0; i < sk_OPENSSL_STRING_num(randfiles); i++) {
p = sk_OPENSSL_STRING_value(randfiles, i);
if (!loadfiles(p))
ret = 0;
}
sk_OPENSSL_STRING_free(randfiles);
return ret;
}
int app_RAND_write(void)
{
int ret = 1;
if (save_rand_file == NULL)
return 1;
if (RAND_write_file(save_rand_file) == -1) {
BIO_printf(bio_err, "Cannot write random bytes:\n");
ERR_print_errors(bio_err);
ret = 0;
}
OPENSSL_free(save_rand_file);
save_rand_file = NULL;
return ret;
}
/*
* See comments in opt_verify for explanation of this.
*/
enum r_range { OPT_R_ENUM };
int opt_rand(int opt)
{
switch ((enum r_range)opt) {
case OPT_R__FIRST:
case OPT_R__LAST:
break;
case OPT_R_RAND:
if (randfiles == NULL
&& (randfiles = sk_OPENSSL_STRING_new_null()) == NULL)
return 0;
if (!sk_OPENSSL_STRING_push(randfiles, opt_arg()))
return 0;
break;
case OPT_R_WRITERAND:
OPENSSL_free(save_rand_file);
save_rand_file = OPENSSL_strdup(opt_arg());
if (save_rand_file == NULL)
return 0;
break;
}
return 1;
}
| 3,023 | 23.585366 | 74 |
c
|
openssl
|
openssl-master/apps/lib/app_x509.c
|
/*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include "apps.h"
/*
* X509_ctrl_str() is sorely lacking in libcrypto, but is still needed to
* allow the application to process verification options in a manner similar
* to signature or other options that pass through EVP_PKEY_CTX_ctrl_str(),
* for uniformity.
*
* As soon as more stuff is added, the code will need serious rework. For
* the moment, it only handles the FIPS 196 / SM2 distinguishing ID.
*/
#ifdef EVP_PKEY_CTRL_SET1_ID
static ASN1_OCTET_STRING *mk_octet_string(void *value, size_t value_n)
{
ASN1_OCTET_STRING *v = ASN1_OCTET_STRING_new();
if (v == NULL) {
BIO_printf(bio_err, "error: allocation failed\n");
} else if (!ASN1_OCTET_STRING_set(v, value, (int)value_n)) {
ASN1_OCTET_STRING_free(v);
v = NULL;
}
return v;
}
#endif
static int x509_ctrl(void *object, int cmd, void *value, size_t value_n)
{
switch (cmd) {
#ifdef EVP_PKEY_CTRL_SET1_ID
case EVP_PKEY_CTRL_SET1_ID:
{
ASN1_OCTET_STRING *v = mk_octet_string(value, value_n);
if (v == NULL) {
BIO_printf(bio_err,
"error: setting distinguishing ID in certificate failed\n");
return 0;
}
X509_set0_distinguishing_id(object, v);
return 1;
}
#endif
default:
break;
}
return -2; /* typical EVP_PKEY return for "unsupported" */
}
static int x509_req_ctrl(void *object, int cmd, void *value, size_t value_n)
{
switch (cmd) {
#ifdef EVP_PKEY_CTRL_SET1_ID
case EVP_PKEY_CTRL_SET1_ID:
{
ASN1_OCTET_STRING *v = mk_octet_string(value, value_n);
if (v == NULL) {
BIO_printf(bio_err,
"error: setting distinguishing ID in certificate signing request failed\n");
return 0;
}
X509_REQ_set0_distinguishing_id(object, v);
return 1;
}
#endif
default:
break;
}
return -2; /* typical EVP_PKEY return for "unsupported" */
}
static int do_x509_ctrl_string(int (*ctrl)(void *object, int cmd,
void *value, size_t value_n),
void *object, const char *value)
{
int rv = 0;
char *stmp, *vtmp = NULL;
size_t vtmp_len = 0;
int cmd = 0; /* Will get command values that make sense somehow */
stmp = OPENSSL_strdup(value);
if (stmp == NULL)
return -1;
vtmp = strchr(stmp, ':');
if (vtmp != NULL) {
*vtmp = 0;
vtmp++;
vtmp_len = strlen(vtmp);
}
if (strcmp(stmp, "distid") == 0) {
#ifdef EVP_PKEY_CTRL_SET1_ID
cmd = EVP_PKEY_CTRL_SET1_ID; /* ... except we put it in X509 */
#endif
} else if (strcmp(stmp, "hexdistid") == 0) {
if (vtmp != NULL) {
void *hexid;
long hexid_len = 0;
hexid = OPENSSL_hexstr2buf((const char *)vtmp, &hexid_len);
OPENSSL_free(stmp);
stmp = vtmp = hexid;
vtmp_len = (size_t)hexid_len;
}
#ifdef EVP_PKEY_CTRL_SET1_ID
cmd = EVP_PKEY_CTRL_SET1_ID; /* ... except we put it in X509 */
#endif
}
rv = ctrl(object, cmd, vtmp, vtmp_len);
OPENSSL_free(stmp);
return rv;
}
int x509_ctrl_string(X509 *x, const char *value)
{
return do_x509_ctrl_string(x509_ctrl, x, value);
}
int x509_req_ctrl_string(X509_REQ *x, const char *value)
{
return do_x509_ctrl_string(x509_req_ctrl, x, value);
}
| 3,879 | 27.115942 | 103 |
c
|
openssl
|
openssl-master/apps/lib/apps_opt_printf.c
|
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "opt.h"
#include <openssl/ui.h>
#include "apps_ui.h"
/* This function is defined here due to visibility of bio_err */
int opt_printf_stderr(const char *fmt, ...)
{
va_list ap;
int ret;
va_start(ap, fmt);
ret = BIO_vprintf(bio_err, fmt, ap);
va_end(ap);
return ret;
}
| 635 | 23.461538 | 74 |
c
|
openssl
|
openssl-master/apps/lib/apps_ui.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/err.h>
#include <openssl/ui.h>
#include "apps_ui.h"
static UI_METHOD *ui_method = NULL;
static const UI_METHOD *ui_base_method = NULL;
static int ui_open(UI *ui)
{
int (*opener)(UI *ui) = UI_method_get_opener(ui_base_method);
if (opener != NULL)
return opener(ui);
return 1;
}
static int ui_read(UI *ui, UI_STRING *uis)
{
int (*reader)(UI *ui, UI_STRING *uis) = NULL;
if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
&& UI_get0_user_data(ui)) {
switch (UI_get_string_type(uis)) {
case UIT_PROMPT:
case UIT_VERIFY:
{
const char *password =
((PW_CB_DATA *)UI_get0_user_data(ui))->password;
if (password != NULL) {
UI_set_result(ui, uis, password);
return 1;
}
}
break;
case UIT_NONE:
case UIT_BOOLEAN:
case UIT_INFO:
case UIT_ERROR:
break;
}
}
reader = UI_method_get_reader(ui_base_method);
if (reader != NULL)
return reader(ui, uis);
/* Default to the empty password if we've got nothing better */
UI_set_result(ui, uis, "");
return 1;
}
static int ui_write(UI *ui, UI_STRING *uis)
{
int (*writer)(UI *ui, UI_STRING *uis) = NULL;
if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
&& UI_get0_user_data(ui)) {
switch (UI_get_string_type(uis)) {
case UIT_PROMPT:
case UIT_VERIFY:
{
const char *password =
((PW_CB_DATA *)UI_get0_user_data(ui))->password;
if (password != NULL)
return 1;
}
break;
case UIT_NONE:
case UIT_BOOLEAN:
case UIT_INFO:
case UIT_ERROR:
break;
}
}
writer = UI_method_get_writer(ui_base_method);
if (writer != NULL)
return writer(ui, uis);
return 1;
}
static int ui_close(UI *ui)
{
int (*closer)(UI *ui) = UI_method_get_closer(ui_base_method);
if (closer != NULL)
return closer(ui);
return 1;
}
/* object_name defaults to prompt_info from ui user data if present */
static char *ui_prompt_construct(UI *ui, const char *phrase_desc,
const char *object_name)
{
PW_CB_DATA *cb_data = (PW_CB_DATA *)UI_get0_user_data(ui);
if (phrase_desc == NULL)
phrase_desc = "pass phrase";
if (object_name == NULL && cb_data != NULL)
object_name = cb_data->prompt_info;
return UI_construct_prompt(NULL, phrase_desc, object_name);
}
int set_base_ui_method(const UI_METHOD *ui_meth)
{
if (ui_meth == NULL)
ui_meth = UI_null();
ui_base_method = ui_meth;
return 1;
}
int setup_ui_method(void)
{
ui_base_method = UI_null();
#ifndef OPENSSL_NO_UI_CONSOLE
ui_base_method = UI_OpenSSL();
#endif
ui_method = UI_create_method("OpenSSL application user interface");
return ui_method != NULL
&& 0 == UI_method_set_opener(ui_method, ui_open)
&& 0 == UI_method_set_reader(ui_method, ui_read)
&& 0 == UI_method_set_writer(ui_method, ui_write)
&& 0 == UI_method_set_closer(ui_method, ui_close)
&& 0 == UI_method_set_prompt_constructor(ui_method,
ui_prompt_construct);
}
void destroy_ui_method(void)
{
if (ui_method != NULL) {
UI_destroy_method(ui_method);
ui_method = NULL;
}
}
const UI_METHOD *get_ui_method(void)
{
return ui_method;
}
static void *ui_malloc(int sz, const char *what)
{
void *vp = OPENSSL_malloc(sz);
if (vp == NULL) {
BIO_printf(bio_err, "Could not allocate %d bytes for %s\n", sz, what);
ERR_print_errors(bio_err);
exit(1);
}
return vp;
}
int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_data)
{
int res = 0;
UI *ui;
int ok = 0;
char *buff = NULL;
int ui_flags = 0;
const char *prompt_info = NULL;
char *prompt;
if ((ui = UI_new_method(ui_method)) == NULL)
return 0;
if (cb_data != NULL && cb_data->prompt_info != NULL)
prompt_info = cb_data->prompt_info;
prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
if (prompt == NULL) {
BIO_printf(bio_err, "Out of memory\n");
UI_free(ui);
return 0;
}
ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
/* We know that there is no previous user data to return to us */
(void)UI_add_user_data(ui, cb_data);
ok = UI_add_input_string(ui, prompt, ui_flags, buf,
PW_MIN_LENGTH, bufsiz - 1);
if (ok >= 0 && verify) {
buff = ui_malloc(bufsiz, "password buffer");
ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
PW_MIN_LENGTH, bufsiz - 1, buf);
}
if (ok >= 0)
do {
ok = UI_process(ui);
} while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
OPENSSL_clear_free(buff, (unsigned int)bufsiz);
if (ok >= 0)
res = strlen(buf);
if (ok == -1) {
BIO_printf(bio_err, "User interface error\n");
ERR_print_errors(bio_err);
OPENSSL_cleanse(buf, (unsigned int)bufsiz);
res = 0;
}
if (ok == -2) {
BIO_printf(bio_err, "aborted!\n");
OPENSSL_cleanse(buf, (unsigned int)bufsiz);
res = 0;
}
UI_free(ui);
OPENSSL_free(prompt);
return res;
}
| 5,973 | 25.669643 | 78 |
c
|
openssl
|
openssl-master/apps/lib/cmp_mock_srv.c
|
/*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Siemens AG 2018-2020
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or atf
* https://www.openssl.org/source/license.html
*/
#include "apps.h"
#include "cmp_mock_srv.h"
#include <openssl/cmp.h>
#include <openssl/err.h>
#include <openssl/cmperr.h>
/* the context for the CMP mock server */
typedef struct
{
X509 *refCert; /* cert to expect for oldCertID in kur/rr msg */
X509 *certOut; /* certificate to be returned in cp/ip/kup msg */
STACK_OF(X509) *chainOut; /* chain of certOut to add to extraCerts field */
STACK_OF(X509) *caPubsOut; /* used in caPubs of ip and in caCerts of genp */
X509 *newWithNew; /* to return in newWithNew of rootKeyUpdate */
X509 *newWithOld; /* to return in newWithOld of rootKeyUpdate */
X509 *oldWithNew; /* to return in oldWithNew of rootKeyUpdate */
OSSL_CMP_PKISI *statusOut; /* status for ip/cp/kup/rp msg unless polling */
int sendError; /* send error response on given request type */
OSSL_CMP_MSG *certReq; /* ir/cr/p10cr/kur remembered while polling */
int pollCount; /* number of polls before actual cert response */
int curr_pollCount; /* number of polls so far for current request */
int checkAfterTime; /* time the client should wait between polling */
} mock_srv_ctx;
static void mock_srv_ctx_free(mock_srv_ctx *ctx)
{
if (ctx == NULL)
return;
OSSL_CMP_PKISI_free(ctx->statusOut);
X509_free(ctx->refCert);
X509_free(ctx->certOut);
OSSL_STACK_OF_X509_free(ctx->chainOut);
OSSL_STACK_OF_X509_free(ctx->caPubsOut);
OSSL_CMP_MSG_free(ctx->certReq);
OPENSSL_free(ctx);
}
static mock_srv_ctx *mock_srv_ctx_new(void)
{
mock_srv_ctx *ctx = OPENSSL_zalloc(sizeof(mock_srv_ctx));
if (ctx == NULL)
goto err;
if ((ctx->statusOut = OSSL_CMP_PKISI_new()) == NULL)
goto err;
ctx->sendError = -1;
/* all other elements are initialized to 0 or NULL, respectively */
return ctx;
err:
mock_srv_ctx_free(ctx);
return NULL;
}
#define DEFINE_OSSL_SET1_CERT(FIELD) \
int ossl_cmp_mock_srv_set1_##FIELD(OSSL_CMP_SRV_CTX *srv_ctx, \
X509 *cert) \
{ \
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); \
\
if (ctx == NULL) { \
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
return 0; \
} \
if (cert == NULL || X509_up_ref(cert)) { \
X509_free(ctx->FIELD); \
ctx->FIELD = cert; \
return 1; \
} \
return 0; \
}
DEFINE_OSSL_SET1_CERT(refCert)
DEFINE_OSSL_SET1_CERT(certOut)
int ossl_cmp_mock_srv_set1_chainOut(OSSL_CMP_SRV_CTX *srv_ctx,
STACK_OF(X509) *chain)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
STACK_OF(X509) *chain_copy = NULL;
if (ctx == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (chain != NULL && (chain_copy = X509_chain_up_ref(chain)) == NULL)
return 0;
OSSL_STACK_OF_X509_free(ctx->chainOut);
ctx->chainOut = chain_copy;
return 1;
}
int ossl_cmp_mock_srv_set1_caPubsOut(OSSL_CMP_SRV_CTX *srv_ctx,
STACK_OF(X509) *caPubs)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
STACK_OF(X509) *caPubs_copy = NULL;
if (ctx == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (caPubs != NULL && (caPubs_copy = X509_chain_up_ref(caPubs)) == NULL)
return 0;
OSSL_STACK_OF_X509_free(ctx->caPubsOut);
ctx->caPubsOut = caPubs_copy;
return 1;
}
DEFINE_OSSL_SET1_CERT(newWithNew)
DEFINE_OSSL_SET1_CERT(newWithOld)
DEFINE_OSSL_SET1_CERT(oldWithNew)
int ossl_cmp_mock_srv_set_statusInfo(OSSL_CMP_SRV_CTX *srv_ctx, int status,
int fail_info, const char *text)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
OSSL_CMP_PKISI *si;
if (ctx == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if ((si = OSSL_CMP_STATUSINFO_new(status, fail_info, text)) == NULL)
return 0;
OSSL_CMP_PKISI_free(ctx->statusOut);
ctx->statusOut = si;
return 1;
}
int ossl_cmp_mock_srv_set_sendError(OSSL_CMP_SRV_CTX *srv_ctx, int bodytype)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
if (ctx == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
/* might check bodytype, but this would require exporting all body types */
ctx->sendError = bodytype;
return 1;
}
int ossl_cmp_mock_srv_set_pollCount(OSSL_CMP_SRV_CTX *srv_ctx, int count)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
if (ctx == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (count < 0) {
ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS);
return 0;
}
ctx->pollCount = count;
return 1;
}
int ossl_cmp_mock_srv_set_checkAfterTime(OSSL_CMP_SRV_CTX *srv_ctx, int sec)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
if (ctx == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
ctx->checkAfterTime = sec;
return 1;
}
/* check for matching reference cert components, as far as given */
static int refcert_cmp(const X509 *refcert,
const X509_NAME *issuer, const ASN1_INTEGER *serial)
{
const X509_NAME *ref_issuer;
const ASN1_INTEGER *ref_serial;
if (refcert == NULL)
return 1;
ref_issuer = X509_get_issuer_name(refcert);
ref_serial = X509_get0_serialNumber(refcert);
return (ref_issuer == NULL || X509_NAME_cmp(issuer, ref_issuer) == 0)
&& (ref_serial == NULL || ASN1_INTEGER_cmp(serial, ref_serial) == 0);
}
static OSSL_CMP_PKISI *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *cert_req,
ossl_unused int certReqId,
const OSSL_CRMF_MSG *crm,
const X509_REQ *p10cr,
X509 **certOut,
STACK_OF(X509) **chainOut,
STACK_OF(X509) **caPubs)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
int bodytype;
OSSL_CMP_PKISI *si = NULL;
if (ctx == NULL || cert_req == NULL
|| certOut == NULL || chainOut == NULL || caPubs == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return NULL;
}
bodytype = OSSL_CMP_MSG_get_bodytype(cert_req);
if (ctx->sendError == 1 || ctx->sendError == bodytype) {
ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE);
return NULL;
}
*certOut = NULL;
*chainOut = NULL;
*caPubs = NULL;
if (ctx->pollCount > 0 && ctx->curr_pollCount == 0) {
/* start polling */
if (ctx->certReq != NULL) {
/* already in polling mode */
ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY);
return NULL;
}
if ((ctx->certReq = OSSL_CMP_MSG_dup(cert_req)) == NULL)
return NULL;
return OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_waiting, 0, NULL);
}
if (ctx->curr_pollCount >= ctx->pollCount)
/* give final response after polling */
ctx->curr_pollCount = 0;
/* accept cert update request only for the reference cert, if given */
if (bodytype == OSSL_CMP_KUR
&& crm != NULL /* thus not p10cr */ && ctx->refCert != NULL) {
const OSSL_CRMF_CERTID *cid = OSSL_CRMF_MSG_get0_regCtrl_oldCertID(crm);
if (cid == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_CERTID);
return NULL;
}
if (!refcert_cmp(ctx->refCert,
OSSL_CRMF_CERTID_get0_issuer(cid),
OSSL_CRMF_CERTID_get0_serialNumber(cid))) {
ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_CERTID);
return NULL;
}
}
if (ctx->certOut != NULL
&& (*certOut = X509_dup(ctx->certOut)) == NULL)
/* Should return a cert produced from request template, see FR #16054 */
goto err;
if (ctx->chainOut != NULL
&& (*chainOut = X509_chain_up_ref(ctx->chainOut)) == NULL)
goto err;
if (ctx->caPubsOut != NULL /* OSSL_CMP_PKIBODY_IP not visible here */
&& (*caPubs = X509_chain_up_ref(ctx->caPubsOut)) == NULL)
goto err;
if (ctx->statusOut != NULL
&& (si = OSSL_CMP_PKISI_dup(ctx->statusOut)) == NULL)
goto err;
return si;
err:
X509_free(*certOut);
*certOut = NULL;
OSSL_STACK_OF_X509_free(*chainOut);
*chainOut = NULL;
OSSL_STACK_OF_X509_free(*caPubs);
*caPubs = NULL;
return NULL;
}
static OSSL_CMP_PKISI *process_rr(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *rr,
const X509_NAME *issuer,
const ASN1_INTEGER *serial)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
if (ctx == NULL || rr == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return NULL;
}
if (ctx->sendError == 1
|| ctx->sendError == OSSL_CMP_MSG_get_bodytype(rr)) {
ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE);
return NULL;
}
/* allow any RR derived from CSR which does not include issuer and serial */
if ((issuer != NULL || serial != NULL)
/* accept revocation only for the reference cert, if given */
&& !refcert_cmp(ctx->refCert, issuer, serial)) {
ERR_raise_data(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED,
"wrong certificate to revoke");
return NULL;
}
return OSSL_CMP_PKISI_dup(ctx->statusOut);
}
static OSSL_CMP_ITAV *process_genm_itav(mock_srv_ctx *ctx, int req_nid,
const OSSL_CMP_ITAV *req)
{
OSSL_CMP_ITAV *rsp;
switch (req_nid) {
case NID_id_it_caCerts:
rsp = OSSL_CMP_ITAV_new_caCerts(ctx->caPubsOut);
break;
case NID_id_it_rootCaCert:
rsp = OSSL_CMP_ITAV_new_rootCaKeyUpdate(ctx->newWithNew,
ctx->newWithOld,
ctx->oldWithNew);
break;
default:
rsp = OSSL_CMP_ITAV_dup(req);
}
return rsp;
}
static int process_genm(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *genm,
const STACK_OF(OSSL_CMP_ITAV) *in,
STACK_OF(OSSL_CMP_ITAV) **out)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
if (ctx == NULL || genm == NULL || in == NULL || out == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (ctx->sendError == 1
|| ctx->sendError == OSSL_CMP_MSG_get_bodytype(genm)
|| sk_OSSL_CMP_ITAV_num(in) > 1) {
ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE);
return 0;
}
if (sk_OSSL_CMP_ITAV_num(in) == 1) {
OSSL_CMP_ITAV *req = sk_OSSL_CMP_ITAV_value(in, 0), *rsp;
ASN1_OBJECT *obj = OSSL_CMP_ITAV_get0_type(req);
if ((*out = sk_OSSL_CMP_ITAV_new_reserve(NULL, 1)) == NULL)
return 0;
rsp = process_genm_itav(ctx, OBJ_obj2nid(obj), req);
if (rsp != NULL && sk_OSSL_CMP_ITAV_push(*out, rsp))
return 1;
sk_OSSL_CMP_ITAV_free(*out);
return 0;
}
*out = sk_OSSL_CMP_ITAV_deep_copy(in, OSSL_CMP_ITAV_dup,
OSSL_CMP_ITAV_free);
return *out != NULL;
}
static void process_error(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *error,
const OSSL_CMP_PKISI *statusInfo,
const ASN1_INTEGER *errorCode,
const OSSL_CMP_PKIFREETEXT *errorDetails)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
char buf[OSSL_CMP_PKISI_BUFLEN];
char *sibuf;
int i;
if (ctx == NULL || error == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return;
}
BIO_printf(bio_err, "mock server received error:\n");
if (statusInfo == NULL) {
BIO_printf(bio_err, "pkiStatusInfo absent\n");
} else {
sibuf = OSSL_CMP_snprint_PKIStatusInfo(statusInfo, buf, sizeof(buf));
BIO_printf(bio_err, "pkiStatusInfo: %s\n",
sibuf != NULL ? sibuf: "<invalid>");
}
if (errorCode == NULL)
BIO_printf(bio_err, "errorCode absent\n");
else
BIO_printf(bio_err, "errorCode: %ld\n", ASN1_INTEGER_get(errorCode));
if (sk_ASN1_UTF8STRING_num(errorDetails) <= 0) {
BIO_printf(bio_err, "errorDetails absent\n");
} else {
BIO_printf(bio_err, "errorDetails: ");
for (i = 0; i < sk_ASN1_UTF8STRING_num(errorDetails); i++) {
if (i > 0)
BIO_printf(bio_err, ", ");
ASN1_STRING_print_ex(bio_err,
sk_ASN1_UTF8STRING_value(errorDetails, i),
ASN1_STRFLGS_ESC_QUOTE);
}
BIO_printf(bio_err, "\n");
}
}
static int process_certConf(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *certConf,
ossl_unused int certReqId,
const ASN1_OCTET_STRING *certHash,
const OSSL_CMP_PKISI *si)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
ASN1_OCTET_STRING *digest;
if (ctx == NULL || certConf == NULL || certHash == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (ctx->sendError == 1
|| ctx->sendError == OSSL_CMP_MSG_get_bodytype(certConf)
|| ctx->certOut == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE);
return 0;
}
if ((digest = X509_digest_sig(ctx->certOut, NULL, NULL)) == NULL)
return 0;
if (ASN1_OCTET_STRING_cmp(certHash, digest) != 0) {
ASN1_OCTET_STRING_free(digest);
ERR_raise(ERR_LIB_CMP, CMP_R_CERTHASH_UNMATCHED);
return 0;
}
ASN1_OCTET_STRING_free(digest);
return 1;
}
static int process_pollReq(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *pollReq,
ossl_unused int certReqId,
OSSL_CMP_MSG **certReq, int64_t *check_after)
{
mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx);
if (ctx == NULL || pollReq == NULL
|| certReq == NULL || check_after == NULL) {
ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
return 0;
}
if (ctx->sendError == 1
|| ctx->sendError == OSSL_CMP_MSG_get_bodytype(pollReq)) {
*certReq = NULL;
ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE);
return 0;
}
if (ctx->certReq == NULL) {
/* not currently in polling mode */
*certReq = NULL;
ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY);
return 0;
}
if (++ctx->curr_pollCount >= ctx->pollCount) {
/* end polling */
*certReq = ctx->certReq;
ctx->certReq = NULL;
*check_after = 0;
} else {
*certReq = NULL;
*check_after = ctx->checkAfterTime;
}
return 1;
}
OSSL_CMP_SRV_CTX *ossl_cmp_mock_srv_new(OSSL_LIB_CTX *libctx, const char *propq)
{
OSSL_CMP_SRV_CTX *srv_ctx = OSSL_CMP_SRV_CTX_new(libctx, propq);
mock_srv_ctx *ctx = mock_srv_ctx_new();
if (srv_ctx != NULL && ctx != NULL
&& OSSL_CMP_SRV_CTX_init(srv_ctx, ctx, process_cert_request,
process_rr, process_genm, process_error,
process_certConf, process_pollReq))
return srv_ctx;
mock_srv_ctx_free(ctx);
OSSL_CMP_SRV_CTX_free(srv_ctx);
return NULL;
}
void ossl_cmp_mock_srv_free(OSSL_CMP_SRV_CTX *srv_ctx)
{
if (srv_ctx != NULL)
mock_srv_ctx_free(OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx));
OSSL_CMP_SRV_CTX_free(srv_ctx);
}
| 16,841 | 32.416667 | 80 |
c
|
openssl
|
openssl-master/apps/lib/columns.c
|
/*
* Copyright 2017-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include "apps.h"
#include "function.h"
void calculate_columns(FUNCTION *functions, DISPLAY_COLUMNS *dc)
{
FUNCTION *f;
int len, maxlen = 0;
for (f = functions; f->name != NULL; ++f)
if (f->type == FT_general || f->type == FT_md || f->type == FT_cipher)
if ((len = strlen(f->name)) > maxlen)
maxlen = len;
dc->width = maxlen + 2;
dc->columns = (80 - 1) / dc->width;
}
| 785 | 27.071429 | 78 |
c
|
openssl
|
openssl-master/apps/lib/engine.c
|
/*
* Copyright 2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Here is a set of wrappers for the ENGINE API, which are no-ops when the
* ENGINE API is disabled / removed.
* We need to suppress deprecation warnings to make this work.
*/
#define OPENSSL_SUPPRESS_DEPRECATED
#include <string.h> /* strcmp */
#include <openssl/types.h> /* Ensure we have the ENGINE type, regardless */
#include <openssl/err.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#include "apps.h"
#ifndef OPENSSL_NO_ENGINE
/* Try to load an engine in a shareable library */
static ENGINE *try_load_engine(const char *engine)
{
ENGINE *e = NULL;
if ((e = ENGINE_by_id("dynamic")) != NULL) {
if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
|| !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
ENGINE_free(e);
e = NULL;
}
}
return e;
}
#endif
ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug)
{
ENGINE *e = NULL;
#ifndef OPENSSL_NO_ENGINE
if (id != NULL) {
if (strcmp(id, "auto") == 0) {
BIO_printf(bio_err, "Enabling auto ENGINE support\n");
ENGINE_register_all_complete();
return NULL;
}
if ((e = ENGINE_by_id(id)) == NULL
&& (e = try_load_engine(id)) == NULL) {
BIO_printf(bio_err, "Invalid engine \"%s\"\n", id);
ERR_print_errors(bio_err);
return NULL;
}
if (debug)
(void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0,
(void *)get_ui_method(), 0, 1)
|| !ENGINE_set_default(e, methods)) {
BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e));
ERR_print_errors(bio_err);
ENGINE_free(e);
return NULL;
}
BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e));
}
#endif
return e;
}
void release_engine(ENGINE *e)
{
#ifndef OPENSSL_NO_ENGINE
/* Free our "structural" reference. */
ENGINE_free(e);
#endif
}
int init_engine(ENGINE *e)
{
int rv = 1;
#ifndef OPENSSL_NO_ENGINE
rv = ENGINE_init(e);
#endif
return rv;
}
int finish_engine(ENGINE *e)
{
int rv = 1;
#ifndef OPENSSL_NO_ENGINE
rv = ENGINE_finish(e);
#endif
return rv;
}
char *make_engine_uri(ENGINE *e, const char *key_id, const char *desc)
{
char *new_uri = NULL;
#ifndef OPENSSL_NO_ENGINE
if (e == NULL) {
BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
} else if (key_id == NULL) {
BIO_printf(bio_err, "No engine key id specified for loading %s\n", desc);
} else {
const char *engineid = ENGINE_get_id(e);
size_t uri_sz =
sizeof(ENGINE_SCHEME_COLON) - 1
+ strlen(engineid)
+ 1 /* : */
+ strlen(key_id)
+ 1 /* \0 */
;
new_uri = OPENSSL_malloc(uri_sz);
if (new_uri != NULL) {
OPENSSL_strlcpy(new_uri, ENGINE_SCHEME_COLON, uri_sz);
OPENSSL_strlcat(new_uri, engineid, uri_sz);
OPENSSL_strlcat(new_uri, ":", uri_sz);
OPENSSL_strlcat(new_uri, key_id, uri_sz);
}
}
#else
BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
#endif
return new_uri;
}
int get_legacy_pkey_id(OSSL_LIB_CTX *libctx, const char *algname, ENGINE *e)
{
const EVP_PKEY_ASN1_METHOD *ameth;
ENGINE *tmpeng = NULL;
int pkey_id = NID_undef;
ERR_set_mark();
ameth = EVP_PKEY_asn1_find_str(&tmpeng, algname, -1);
#if !defined(OPENSSL_NO_ENGINE)
ENGINE_finish(tmpeng);
if (ameth == NULL && e != NULL)
ameth = ENGINE_get_pkey_asn1_meth_str(e, algname, -1);
else
#endif
/* We're only interested if it comes from an ENGINE */
if (tmpeng == NULL)
ameth = NULL;
ERR_pop_to_mark();
if (ameth == NULL)
return NID_undef;
EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth);
return pkey_id;
}
const EVP_MD *get_digest_from_engine(const char *name)
{
#ifndef OPENSSL_NO_ENGINE
ENGINE *eng;
eng = ENGINE_get_digest_engine(OBJ_sn2nid(name));
if (eng != NULL) {
ENGINE_finish(eng);
return EVP_get_digestbyname(name);
}
#endif
return NULL;
}
const EVP_CIPHER *get_cipher_from_engine(const char *name)
{
#ifndef OPENSSL_NO_ENGINE
ENGINE *eng;
eng = ENGINE_get_cipher_engine(OBJ_sn2nid(name));
if (eng != NULL) {
ENGINE_finish(eng);
return EVP_get_cipherbyname(name);
}
#endif
return NULL;
}
| 4,968 | 24.613402 | 81 |
c
|
openssl
|
openssl-master/apps/lib/engine_loader.c
|
/*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Here is an STORE loader for ENGINE backed keys. It relies on deprecated
* functions, and therefore need to have deprecation warnings suppressed.
* This file is not compiled at all in a '--api=3 no-deprecated' configuration.
*/
#define OPENSSL_SUPPRESS_DEPRECATED
#include "apps.h"
#ifndef OPENSSL_NO_ENGINE
# include <stdarg.h>
# include <string.h>
# include <openssl/engine.h>
# include <openssl/store.h>
/*
* Support for legacy private engine keys via the 'org.openssl.engine:' scheme
*
* org.openssl.engine:{engineid}:{keyid}
*
* Note: we ONLY support ENGINE_load_private_key() and ENGINE_load_public_key()
* Note 2: This scheme has a precedent in code in PKIX-SSH. for exactly
* this sort of purpose.
*/
/* Local definition of OSSL_STORE_LOADER_CTX */
struct ossl_store_loader_ctx_st {
ENGINE *e; /* Structural reference */
char *keyid;
int expected;
int loaded; /* 0 = key not loaded yet, 1 = key loaded */
};
static OSSL_STORE_LOADER_CTX *OSSL_STORE_LOADER_CTX_new(ENGINE *e, char *keyid)
{
OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx != NULL) {
ctx->e = e;
ctx->keyid = keyid;
}
return ctx;
}
static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
{
if (ctx != NULL) {
ENGINE_free(ctx->e);
OPENSSL_free(ctx->keyid);
OPENSSL_free(ctx);
}
}
static OSSL_STORE_LOADER_CTX *engine_open(const OSSL_STORE_LOADER *loader,
const char *uri,
const UI_METHOD *ui_method,
void *ui_data)
{
const char *p = uri, *q;
ENGINE *e = NULL;
char *keyid = NULL;
OSSL_STORE_LOADER_CTX *ctx = NULL;
if (!CHECK_AND_SKIP_CASE_PREFIX(p, ENGINE_SCHEME_COLON))
return NULL;
/* Look for engine ID */
q = strchr(p, ':');
if (q != NULL /* There is both an engine ID and a key ID */
&& p[0] != ':' /* The engine ID is at least one character */
&& q[1] != '\0') { /* The key ID is at least one character */
char engineid[256];
size_t engineid_l = q - p;
strncpy(engineid, p, engineid_l);
engineid[engineid_l] = '\0';
e = ENGINE_by_id(engineid);
keyid = OPENSSL_strdup(q + 1);
}
if (e != NULL && keyid != NULL)
ctx = OSSL_STORE_LOADER_CTX_new(e, keyid);
if (ctx == NULL) {
OPENSSL_free(keyid);
ENGINE_free(e);
}
return ctx;
}
static int engine_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
{
if (expected == 0
|| expected == OSSL_STORE_INFO_PUBKEY
|| expected == OSSL_STORE_INFO_PKEY) {
ctx->expected = expected;
return 1;
}
return 0;
}
static OSSL_STORE_INFO *engine_load(OSSL_STORE_LOADER_CTX *ctx,
const UI_METHOD *ui_method, void *ui_data)
{
EVP_PKEY *pkey = NULL, *pubkey = NULL;
OSSL_STORE_INFO *info = NULL;
if (ctx->loaded == 0) {
if (ENGINE_init(ctx->e)) {
if (ctx->expected == 0
|| ctx->expected == OSSL_STORE_INFO_PKEY)
pkey =
ENGINE_load_private_key(ctx->e, ctx->keyid,
(UI_METHOD *)ui_method, ui_data);
if ((pkey == NULL && ctx->expected == 0)
|| ctx->expected == OSSL_STORE_INFO_PUBKEY)
pubkey =
ENGINE_load_public_key(ctx->e, ctx->keyid,
(UI_METHOD *)ui_method, ui_data);
ENGINE_finish(ctx->e);
}
}
ctx->loaded = 1;
if (pubkey != NULL)
info = OSSL_STORE_INFO_new_PUBKEY(pubkey);
else if (pkey != NULL)
info = OSSL_STORE_INFO_new_PKEY(pkey);
if (info == NULL) {
EVP_PKEY_free(pkey);
EVP_PKEY_free(pubkey);
}
return info;
}
static int engine_eof(OSSL_STORE_LOADER_CTX *ctx)
{
return ctx->loaded != 0;
}
static int engine_error(OSSL_STORE_LOADER_CTX *ctx)
{
return 0;
}
static int engine_close(OSSL_STORE_LOADER_CTX *ctx)
{
OSSL_STORE_LOADER_CTX_free(ctx);
return 1;
}
int setup_engine_loader(void)
{
OSSL_STORE_LOADER *loader = NULL;
if ((loader = OSSL_STORE_LOADER_new(NULL, ENGINE_SCHEME)) == NULL
|| !OSSL_STORE_LOADER_set_open(loader, engine_open)
|| !OSSL_STORE_LOADER_set_expect(loader, engine_expect)
|| !OSSL_STORE_LOADER_set_load(loader, engine_load)
|| !OSSL_STORE_LOADER_set_eof(loader, engine_eof)
|| !OSSL_STORE_LOADER_set_error(loader, engine_error)
|| !OSSL_STORE_LOADER_set_close(loader, engine_close)
|| !OSSL_STORE_register_loader(loader)) {
OSSL_STORE_LOADER_free(loader);
loader = NULL;
}
return loader != NULL;
}
void destroy_engine_loader(void)
{
OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader(ENGINE_SCHEME);
OSSL_STORE_LOADER_free(loader);
}
#else /* !OPENSSL_NO_ENGINE */
int setup_engine_loader(void)
{
return 0;
}
void destroy_engine_loader(void)
{
}
#endif
| 5,536 | 26.410891 | 79 |
c
|
openssl
|
openssl-master/apps/lib/http_server.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Very basic HTTP server */
#if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
/*
* On VMS, you need to define this to get the declaration of fileno(). The
* value 2 is to make sure no function defined in POSIX-2 is left undefined.
*/
# define _POSIX_C_SOURCE 2
#endif
#include <ctype.h>
#include "http_server.h"
#include "internal/sockets.h"
#include <openssl/err.h>
#include <openssl/trace.h>
#include <openssl/rand.h>
#include "s_apps.h"
#include "log.h"
#if defined(__TANDEM)
# if defined(OPENSSL_TANDEM_FLOSS)
# include <floss.h(floss_fork)>
# endif
#endif
#define HTTP_PREFIX "HTTP/"
#define HTTP_VERSION_PATT "1." /* allow 1.x */
#define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT
#define HTTP_1_0 HTTP_PREFIX_VERSION"0" /* "HTTP/1.0" */
#define HTTP_VERSION_STR " "HTTP_PREFIX_VERSION
#define log_HTTP(prog, level, text) \
trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, "%s", text)
#define log_HTTP1(prog, level, fmt, arg) \
trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg)
#define log_HTTP2(prog, level, fmt, arg1, arg2) \
trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg1, arg2)
#define log_HTTP3(prog, level, fmt, a1, a2, a3) \
trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, a1, a2, a3)
#ifdef HTTP_DAEMON
int n_responders = 0; /* run multiple responder processes, set by ocsp.c */
int acfd = (int)INVALID_SOCKET;
void socket_timeout(int signum)
{
if (acfd != (int)INVALID_SOCKET)
(void)shutdown(acfd, SHUT_RD);
}
static void killall(int ret, pid_t *kidpids)
{
int i;
for (i = 0; i < n_responders; ++i)
if (kidpids[i] != 0)
(void)kill(kidpids[i], SIGTERM);
OPENSSL_free(kidpids);
OSSL_sleep(1000);
exit(ret);
}
static int termsig = 0;
static void noteterm(int sig)
{
termsig = sig;
}
/*
* Loop spawning up to `multi` child processes, only child processes return
* from this function. The parent process loops until receiving a termination
* signal, kills extant children and exits without returning.
*/
void spawn_loop(const char *prog)
{
pid_t *kidpids = NULL;
int status;
int procs = 0;
int i;
openlog(prog, LOG_PID, LOG_DAEMON);
if (setpgid(0, 0)) {
log_HTTP1(prog, LOG_CRIT,
"error detaching from parent process group: %s",
strerror(errno));
exit(1);
}
kidpids = app_malloc(n_responders * sizeof(*kidpids), "child PID array");
for (i = 0; i < n_responders; ++i)
kidpids[i] = 0;
signal(SIGINT, noteterm);
signal(SIGTERM, noteterm);
while (termsig == 0) {
pid_t fpid;
/*
* Wait for a child to replace when we're at the limit.
* Slow down if a child exited abnormally or waitpid() < 0
*/
while (termsig == 0 && procs >= n_responders) {
if ((fpid = waitpid(-1, &status, 0)) > 0) {
for (i = 0; i < procs; ++i) {
if (kidpids[i] == fpid) {
kidpids[i] = 0;
--procs;
break;
}
}
if (i >= n_responders) {
log_HTTP1(prog, LOG_CRIT,
"internal error: no matching child slot for pid: %ld",
(long)fpid);
killall(1, kidpids);
}
if (status != 0) {
if (WIFEXITED(status)) {
log_HTTP2(prog, LOG_WARNING,
"child process: %ld, exit status: %d",
(long)fpid, WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
char *dumped = "";
# ifdef WCOREDUMP
if (WCOREDUMP(status))
dumped = " (core dumped)";
# endif
log_HTTP3(prog, LOG_WARNING,
"child process: %ld, term signal %d%s",
(long)fpid, WTERMSIG(status), dumped);
}
OSSL_sleep(1000);
}
break;
} else if (errno != EINTR) {
log_HTTP1(prog, LOG_CRIT,
"waitpid() failed: %s", strerror(errno));
killall(1, kidpids);
}
}
if (termsig)
break;
switch (fpid = fork()) {
case -1: /* error */
/* System critically low on memory, pause and try again later */
OSSL_sleep(30000);
break;
case 0: /* child */
OPENSSL_free(kidpids);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
if (termsig)
_exit(0);
if (RAND_poll() <= 0) {
log_HTTP(prog, LOG_CRIT, "RAND_poll() failed");
_exit(1);
}
return;
default: /* parent */
for (i = 0; i < n_responders; ++i) {
if (kidpids[i] == 0) {
kidpids[i] = fpid;
procs++;
break;
}
}
if (i >= n_responders) {
log_HTTP(prog, LOG_CRIT,
"internal error: no free child slots");
killall(1, kidpids);
}
break;
}
}
/* The loop above can only break on termsig */
log_HTTP1(prog, LOG_INFO, "terminating on signal: %d", termsig);
killall(0, kidpids);
}
#endif
#ifndef OPENSSL_NO_SOCK
BIO *http_server_init(const char *prog, const char *port, int verb)
{
BIO *acbio = NULL, *bufbio;
int asock;
int port_num;
if (verb >= 0 && !log_set_verbosity(prog, verb))
return NULL;
bufbio = BIO_new(BIO_f_buffer());
if (bufbio == NULL)
goto err;
acbio = BIO_new(BIO_s_accept());
if (acbio == NULL
|| BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
|| BIO_set_accept_port(acbio, port /* may be "0" */) < 0) {
log_HTTP(prog, LOG_ERR, "error setting up accept BIO");
goto err;
}
BIO_set_accept_bios(acbio, bufbio);
bufbio = NULL;
if (BIO_do_accept(acbio) <= 0) {
log_HTTP1(prog, LOG_ERR, "error setting accept on port %s", port);
goto err;
}
/* Report back what address and port are used */
BIO_get_fd(acbio, &asock);
port_num = report_server_accept(bio_out, asock, 1, 1);
if (port_num == 0) {
log_HTTP(prog, LOG_ERR, "error printing ACCEPT string");
goto err;
}
return acbio;
err:
ERR_print_errors(bio_err);
BIO_free_all(acbio);
BIO_free(bufbio);
return NULL;
}
/*
* Decode %xx URL-decoding in-place. Ignores malformed sequences.
*/
static int urldecode(char *p)
{
unsigned char *out = (unsigned char *)p;
unsigned char *save = out;
for (; *p; p++) {
if (*p != '%') {
*out++ = *p;
} else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
/* Don't check, can't fail because of ixdigit() call. */
*out++ = (OPENSSL_hexchar2int(p[1]) << 4)
| OPENSSL_hexchar2int(p[2]);
p += 2;
} else {
return -1;
}
}
*out = '\0';
return (int)(out - save);
}
/* if *pcbio != NULL, continue given connected session, else accept new */
/* if found_keep_alive != NULL, return this way connection persistence state */
int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq,
char **ppath, BIO **pcbio, BIO *acbio,
int *found_keep_alive,
const char *prog, int accept_get, int timeout)
{
BIO *cbio = *pcbio, *getbio = NULL, *b64 = NULL;
int len;
char reqbuf[2048], inbuf[2048];
char *meth, *url, *end;
ASN1_VALUE *req;
int ret = 0;
*preq = NULL;
if (ppath != NULL)
*ppath = NULL;
if (cbio == NULL) {
char *port;
get_sock_info_address(BIO_get_fd(acbio, NULL), NULL, &port);
if (port == NULL) {
log_HTTP(prog, LOG_ERR, "cannot get port listening on");
goto fatal;
}
log_HTTP1(prog, LOG_DEBUG,
"awaiting new connection on port %s ...", port);
OPENSSL_free(port);
if (BIO_do_accept(acbio) <= 0)
/* Connection loss before accept() is routine, ignore silently */
return ret;
*pcbio = cbio = BIO_pop(acbio);
} else {
log_HTTP(prog, LOG_DEBUG, "awaiting next request ...");
}
if (cbio == NULL) {
/* Cannot call http_server_send_status(..., cbio, ...) */
ret = -1;
goto out;
}
# ifdef HTTP_DAEMON
if (timeout > 0) {
(void)BIO_get_fd(cbio, &acfd);
alarm(timeout);
}
# endif
/* Read the request line. */
len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
if (len == 0)
return ret;
ret = 1;
if (len < 0) {
log_HTTP(prog, LOG_WARNING, "request line read error");
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
if (((end = strchr(reqbuf, '\r')) != NULL && end[1] == '\n')
|| (end = strchr(reqbuf, '\n')) != NULL)
*end = '\0';
if (log_get_verbosity() < LOG_TRACE)
trace_log_message(-1, prog, LOG_INFO,
"received request, 1st line: %s", reqbuf);
log_HTTP(prog, LOG_TRACE, "received request header:");
log_HTTP1(prog, LOG_TRACE, "%s", reqbuf);
if (end == NULL) {
log_HTTP(prog, LOG_WARNING,
"cannot parse HTTP header: missing end of line");
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
url = meth = reqbuf;
if ((accept_get && CHECK_AND_SKIP_PREFIX(url, "GET "))
|| CHECK_AND_SKIP_PREFIX(url, "POST ")) {
/* Expecting (GET|POST) {sp} /URL {sp} HTTP/1.x */
url[-1] = '\0';
while (*url == ' ')
url++;
if (*url != '/') {
log_HTTP2(prog, LOG_WARNING,
"invalid %s -- URL does not begin with '/': %s",
meth, url);
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
url++;
/* Splice off the HTTP version identifier. */
for (end = url; *end != '\0'; end++)
if (*end == ' ')
break;
if (!HAS_PREFIX(end, HTTP_VERSION_STR)) {
log_HTTP2(prog, LOG_WARNING,
"invalid %s -- bad HTTP/version string: %s",
meth, end + 1);
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
*end = '\0';
/* above HTTP 1.0, connection persistence is the default */
if (found_keep_alive != NULL)
*found_keep_alive = end[sizeof(HTTP_VERSION_STR) - 1] > '0';
/*-
* Skip "GET / HTTP..." requests often used by load-balancers.
* 'url' was incremented above to point to the first byte *after*
* the leading slash, so in case 'GET / ' it is now an empty string.
*/
if (strlen(meth) == 3 && url[0] == '\0') {
(void)http_server_send_status(prog, cbio, 200, "OK");
goto out;
}
len = urldecode(url);
if (len < 0) {
log_HTTP2(prog, LOG_WARNING,
"invalid %s request -- bad URL encoding: %s", meth, url);
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
if (strlen(meth) == 3) { /* GET */
if ((getbio = BIO_new_mem_buf(url, len)) == NULL
|| (b64 = BIO_new(BIO_f_base64())) == NULL) {
log_HTTP1(prog, LOG_ERR,
"could not allocate base64 bio with size = %d", len);
goto fatal;
}
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
getbio = BIO_push(b64, getbio);
}
} else {
log_HTTP2(prog, LOG_WARNING,
"HTTP request does not begin with %sPOST: %s",
accept_get ? "GET or " : "", reqbuf);
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
/* chop any further/duplicate leading or trailing '/' */
while (*url == '/')
url++;
while (end >= url + 2 && end[-2] == '/' && end[-1] == '/')
end--;
*end = '\0';
/* Read and skip past the headers. */
for (;;) {
char *key, *value;
len = BIO_gets(cbio, inbuf, sizeof(inbuf));
if (len <= 0) {
log_HTTP(prog, LOG_WARNING, "error reading HTTP header");
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
if (((end = strchr(inbuf, '\r')) != NULL && end[1] == '\n')
|| (end = strchr(inbuf, '\n')) != NULL)
*end = '\0';
log_HTTP1(prog, LOG_TRACE, "%s", *inbuf == '\0' ?
" " /* workaround for "" getting ignored */ : inbuf);
if (end == NULL) {
log_HTTP(prog, LOG_WARNING,
"error parsing HTTP header: missing end of line");
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
if (inbuf[0] == '\0')
break;
key = inbuf;
value = strchr(key, ':');
if (value == NULL) {
log_HTTP(prog, LOG_WARNING,
"error parsing HTTP header: missing ':'");
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
goto out;
}
*(value++) = '\0';
while (*value == ' ')
value++;
/* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
if (found_keep_alive != NULL
&& OPENSSL_strcasecmp(key, "Connection") == 0) {
if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
*found_keep_alive = 1;
else if (OPENSSL_strcasecmp(value, "close") == 0)
*found_keep_alive = 0;
}
}
# ifdef HTTP_DAEMON
/* Clear alarm before we close the client socket */
alarm(0);
timeout = 0;
# endif
/* Try to read and parse request */
req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL);
if (req == NULL) {
log_HTTP(prog, LOG_WARNING,
"error parsing DER-encoded request content");
(void)http_server_send_status(prog, cbio, 400, "Bad Request");
} else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) {
log_HTTP1(prog, LOG_ERR,
"out of memory allocating %zu bytes", strlen(url) + 1);
ASN1_item_free(req, it);
goto fatal;
}
*preq = req;
out:
BIO_free_all(getbio);
# ifdef HTTP_DAEMON
if (timeout > 0)
alarm(0);
acfd = (int)INVALID_SOCKET;
# endif
return ret;
fatal:
(void)http_server_send_status(prog, cbio, 500, "Internal Server Error");
if (ppath != NULL) {
OPENSSL_free(*ppath);
*ppath = NULL;
}
BIO_free_all(cbio);
*pcbio = NULL;
ret = -1;
goto out;
}
/* assumes that cbio does not do an encoding that changes the output length */
int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive,
const char *content_type,
const ASN1_ITEM *it, const ASN1_VALUE *resp)
{
char buf[200], *p;
int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" 200 OK\r\n%s"
"Content-type: %s\r\n"
"Content-Length: %d\r\n",
keep_alive ? "Connection: keep-alive\r\n" : "",
content_type,
ASN1_item_i2d(resp, NULL, it));
if (ret < 0 || (size_t)ret >= sizeof(buf))
return 0;
if (log_get_verbosity() < LOG_TRACE && (p = strchr(buf, '\r')) != NULL)
trace_log_message(-1, prog, LOG_INFO,
"sending response, 1st line: %.*s", (int)(p - buf),
buf);
log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
ret = BIO_printf(cbio, "%s\r\n", buf) > 0
&& ASN1_item_i2d_bio(it, cbio, resp) > 0;
(void)BIO_flush(cbio);
return ret;
}
int http_server_send_status(const char *prog, BIO *cbio,
int status, const char *reason)
{
char buf[200];
int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" %d %s\r\n\r\n",
/* This implicitly cancels keep-alive */
status, reason);
if (ret < 0 || (size_t)ret >= sizeof(buf))
return 0;
log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf);
ret = BIO_printf(cbio, "%s\r\n", buf) > 0;
(void)BIO_flush(cbio);
return ret;
}
#endif
| 17,578 | 31.020036 | 84 |
c
|
openssl
|
openssl-master/apps/lib/log.c
|
/*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/trace.h>
#include "apps.h"
#include "log.h"
static int verbosity = LOG_INFO;
int log_set_verbosity(const char *prog, int level)
{
if (level < LOG_EMERG || level > LOG_TRACE) {
trace_log_message(-1, prog, LOG_ERR,
"Invalid verbosity level %d", level);
return 0;
}
verbosity = level;
return 1;
}
int log_get_verbosity(void)
{
return verbosity;
}
#ifdef HTTP_DAEMON
static int print_syslog(const char *str, size_t len, void *levPtr)
{
int level = *(int *)levPtr;
int ilen = len > MAXERRLEN ? MAXERRLEN : len;
syslog(level, "%.*s", ilen, str);
return ilen;
}
#endif
static void log_with_prefix(const char *prog, const char *fmt, va_list ap)
{
char prefix[80];
BIO *bio, *pre = BIO_new(BIO_f_prefix());
(void)BIO_snprintf(prefix, sizeof(prefix), "%s: ", prog);
(void)BIO_set_prefix(pre, prefix);
bio = BIO_push(pre, bio_err);
(void)BIO_vprintf(bio, fmt, ap);
(void)BIO_printf(bio, "\n");
(void)BIO_flush(bio);
(void)BIO_pop(pre);
BIO_free(pre);
}
/*
* Unfortunately, C before C99 does not define va_copy, so we must
* check if it can be assumed to be present. We do that with an internal
* antifeature macro.
* C versions since C94 define __STDC_VERSION__, so it's enough to
* check its existence and value.
*/
#undef OSSL_NO_C99
#if !defined(__STDC_VERSION__) || __STDC_VERSION__ + 0 < 199900L
# define OSSL_NO_C99
#endif
void trace_log_message(int category,
const char *prog, int level, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
#ifdef OSSL_NO_C99
if (verbosity >= level)
category = -1; /* disabling trace output in addition to logging */
#endif
if (category >= 0 && OSSL_trace_enabled(category)) {
BIO *out = OSSL_trace_begin(category);
#ifndef OSSL_NO_C99
va_list ap_copy;
va_copy(ap_copy, ap);
(void)BIO_vprintf(out, fmt, ap_copy);
va_end(ap_copy);
#else
(void)BIO_vprintf(out, fmt, ap);
#endif
(void)BIO_printf(out, "\n");
OSSL_trace_end(category, out);
}
if (verbosity < level) {
va_end(ap);
return;
}
#ifdef HTTP_DAEMON
if (n_responders != 0) {
vsyslog(level, fmt, ap);
if (level <= LOG_ERR)
ERR_print_errors_cb(print_syslog, &level);
} else
#endif
log_with_prefix(prog, fmt, ap);
va_end(ap);
}
| 2,786 | 24.568807 | 74 |
c
|
openssl
|
openssl-master/apps/lib/names.c
|
/*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/bio.h>
#include <openssl/safestack.h>
#include "names.h"
#include "internal/e_os.h"
int name_cmp(const char * const *a, const char * const *b)
{
return OPENSSL_strcasecmp(*a, *b);
}
void collect_names(const char *name, void *vdata)
{
STACK_OF(OPENSSL_CSTRING) *names = vdata;
sk_OPENSSL_CSTRING_push(names, name);
}
void print_names(BIO *out, STACK_OF(OPENSSL_CSTRING) *names)
{
int i = sk_OPENSSL_CSTRING_num(names);
int j;
sk_OPENSSL_CSTRING_sort(names);
if (i > 1)
BIO_printf(out, "{ ");
for (j = 0; j < i; j++) {
const char *name = sk_OPENSSL_CSTRING_value(names, j);
if (j > 0)
BIO_printf(out, ", ");
BIO_printf(out, "%s", name);
}
if (i > 1)
BIO_printf(out, " }");
}
| 1,146 | 23.934783 | 74 |
c
|
openssl
|
openssl-master/apps/lib/s_socket.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* socket-related functions used by s_client and s_server */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <openssl/opensslconf.h>
/*
* With IPv6, it looks like Digital has mixed up the proper order of
* recursive header file inclusion, resulting in the compiler complaining
* that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
* needed to have fileno() declared correctly... So let's define u_int
*/
#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
# define __U_INT
typedef unsigned int u_int;
#endif
#ifdef _WIN32
# include <process.h>
/* MSVC renamed some POSIX functions to have an underscore prefix. */
# ifdef _MSC_VER
# define getpid _getpid
# endif
#endif
#ifndef OPENSSL_NO_SOCK
# include "apps.h"
# include "s_apps.h"
# include "internal/sockets.h"
# if defined(__TANDEM)
# if defined(OPENSSL_TANDEM_FLOSS)
# include <floss.h(floss_read)>
# endif
# endif
# include <openssl/bio.h>
# include <openssl/err.h>
/* Keep track of our peer's address for the cookie callback */
BIO_ADDR *ourpeer = NULL;
/*
* init_client - helper routine to set up socket communication
* @sock: pointer to storage of resulting socket.
* @host: the hostname or path (for AF_UNIX) to connect to.
* @port: the port to connect to (ignored for AF_UNIX).
* @bindhost: source host or path (for AF_UNIX).
* @bindport: source port (ignored for AF_UNIX).
* @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
* AF_UNSPEC
* @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
* @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
* @tfo: flag to enable TCP Fast Open
* @doconn: whether we should call BIO_connect() on the socket
* @ba_ret: BIO_ADDR for the remote peer, to be freed by caller
*
* This will create a socket and use it to connect to a host:port, or if
* family == AF_UNIX, to the path found in host.
*
* If the host has more than one address, it will try them one by one until
* a successful connection is established. The resulting socket will be
* found in *sock on success, it will be given INVALID_SOCKET otherwise.
*
* Returns 1 on success, 0 on failure.
*/
int init_client(int *sock, const char *host, const char *port,
const char *bindhost, const char *bindport,
int family, int type, int protocol, int tfo, int doconn,
BIO_ADDR **ba_ret)
{
BIO_ADDRINFO *res = NULL;
BIO_ADDRINFO *bindaddr = NULL;
const BIO_ADDRINFO *ai = NULL;
const BIO_ADDRINFO *bi = NULL;
int found = 0;
int ret;
int options = 0;
if (tfo && ba_ret != NULL)
*ba_ret = NULL;
if (BIO_sock_init() != 1)
return 0;
ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
&res);
if (ret == 0) {
ERR_print_errors(bio_err);
return 0;
}
if (bindhost != NULL || bindport != NULL) {
ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,
family, type, protocol, &bindaddr);
if (ret == 0) {
ERR_print_errors (bio_err);
goto out;
}
}
ret = 0;
for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
/* Admittedly, these checks are quite paranoid, we should not get
* anything in the BIO_ADDRINFO chain that we haven't
* asked for. */
OPENSSL_assert((family == AF_UNSPEC
|| family == BIO_ADDRINFO_family(ai))
&& (type == 0 || type == BIO_ADDRINFO_socktype(ai))
&& (protocol == 0
|| protocol == BIO_ADDRINFO_protocol(ai)));
if (bindaddr != NULL) {
for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {
if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))
break;
}
if (bi == NULL)
continue;
++found;
}
*sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
BIO_ADDRINFO_protocol(ai), 0);
if (*sock == INVALID_SOCKET) {
/* Maybe the kernel doesn't support the socket family, even if
* BIO_lookup() added it in the returned result...
*/
continue;
}
if (bi != NULL) {
if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),
BIO_SOCK_REUSEADDR)) {
BIO_closesocket(*sock);
*sock = INVALID_SOCKET;
break;
}
}
#ifndef OPENSSL_NO_SCTP
if (protocol == IPPROTO_SCTP) {
/*
* For SCTP we have to set various options on the socket prior to
* connecting. This is done automatically by BIO_new_dgram_sctp().
* We don't actually need the created BIO though so we free it again
* immediately.
*/
BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
if (tmpbio == NULL) {
ERR_print_errors(bio_err);
return 0;
}
BIO_free(tmpbio);
}
#endif
if (BIO_ADDRINFO_protocol(ai) == IPPROTO_TCP) {
options |= BIO_SOCK_NODELAY;
if (tfo)
options |= BIO_SOCK_TFO;
}
if (doconn && !BIO_connect(*sock, BIO_ADDRINFO_address(ai), options)) {
BIO_closesocket(*sock);
*sock = INVALID_SOCKET;
continue;
}
/* Save the address */
if (tfo || !doconn)
*ba_ret = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
/* Success, don't try any more addresses */
break;
}
if (*sock == INVALID_SOCKET) {
if (bindaddr != NULL && !found) {
BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
#ifdef AF_INET6
BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
#endif
BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
bindhost != NULL ? bindhost : "",
bindport != NULL ? ":" : "",
bindport != NULL ? bindport : "");
ERR_clear_error();
ret = 0;
}
ERR_print_errors(bio_err);
} else {
char *hostname = NULL;
hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1);
if (hostname != NULL) {
BIO_printf(bio_out, "Connecting to %s\n", hostname);
OPENSSL_free(hostname);
}
/* Remove any stale errors from previous connection attempts */
ERR_clear_error();
ret = 1;
}
out:
if (bindaddr != NULL) {
BIO_ADDRINFO_free (bindaddr);
}
BIO_ADDRINFO_free(res);
return ret;
}
void get_sock_info_address(int asock, char **hostname, char **service)
{
union BIO_sock_info_u info;
if (hostname != NULL)
*hostname = NULL;
if (service != NULL)
*service = NULL;
if ((info.addr = BIO_ADDR_new()) != NULL
&& BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)) {
if (hostname != NULL)
*hostname = BIO_ADDR_hostname_string(info.addr, 1);
if (service != NULL)
*service = BIO_ADDR_service_string(info.addr, 1);
}
BIO_ADDR_free(info.addr);
}
int report_server_accept(BIO *out, int asock, int with_address, int with_pid)
{
int success = 1;
if (BIO_printf(out, "ACCEPT") <= 0)
return 0;
if (with_address) {
char *hostname, *service;
get_sock_info_address(asock, &hostname, &service);
success = hostname != NULL && service != NULL;
if (success)
success = BIO_printf(out,
strchr(hostname, ':') == NULL
? /* IPv4 */ " %s:%s"
: /* IPv6 */ " [%s]:%s",
hostname, service) > 0;
else
(void)BIO_printf(out, "unknown:error\n");
OPENSSL_free(hostname);
OPENSSL_free(service);
}
if (with_pid)
success *= BIO_printf(out, " PID=%d", getpid()) > 0;
success *= BIO_printf(out, "\n") > 0;
(void)BIO_flush(out);
return success;
}
/*
* do_server - helper routine to perform a server operation
* @accept_sock: pointer to storage of resulting socket.
* @host: the hostname or path (for AF_UNIX) to connect to.
* @port: the port to connect to (ignored for AF_UNIX).
* @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
* AF_UNSPEC
* @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
* @cb: pointer to a function that receives the accepted socket and
* should perform the communication with the connecting client.
* @context: pointer to memory that's passed verbatim to the cb function.
* @naccept: number of times an incoming connect should be accepted. If -1,
* unlimited number.
*
* This will create a socket and use it to listen to a host:port, or if
* family == AF_UNIX, to the path found in host, then start accepting
* incoming connections and run cb on the resulting socket.
*
* 0 on failure, something other on success.
*/
int do_server(int *accept_sock, const char *host, const char *port,
int family, int type, int protocol, do_server_cb cb,
unsigned char *context, int naccept, BIO *bio_s_out,
int tfo)
{
int asock = 0;
int sock;
int i;
BIO_ADDRINFO *res = NULL;
const BIO_ADDRINFO *next;
int sock_family, sock_type, sock_protocol, sock_port;
const BIO_ADDR *sock_address;
int sock_family_fallback = AF_UNSPEC;
const BIO_ADDR *sock_address_fallback = NULL;
int sock_options = BIO_SOCK_REUSEADDR;
int ret = 0;
if (BIO_sock_init() != 1)
return 0;
if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
&res)) {
ERR_print_errors(bio_err);
return 0;
}
/* Admittedly, these checks are quite paranoid, we should not get
* anything in the BIO_ADDRINFO chain that we haven't asked for */
OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
&& (type == 0 || type == BIO_ADDRINFO_socktype(res))
&& (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
sock_family = BIO_ADDRINFO_family(res);
sock_type = BIO_ADDRINFO_socktype(res);
sock_protocol = BIO_ADDRINFO_protocol(res);
sock_address = BIO_ADDRINFO_address(res);
next = BIO_ADDRINFO_next(res);
if (tfo && sock_type == SOCK_STREAM)
sock_options |= BIO_SOCK_TFO;
#ifdef AF_INET6
if (sock_family == AF_INET6)
sock_options |= BIO_SOCK_V6_ONLY;
if (next != NULL
&& BIO_ADDRINFO_socktype(next) == sock_type
&& BIO_ADDRINFO_protocol(next) == sock_protocol) {
if (sock_family == AF_INET
&& BIO_ADDRINFO_family(next) == AF_INET6) {
/* In case AF_INET6 is returned but not supported by the
* kernel, retry with the first detected address family */
sock_family_fallback = sock_family;
sock_address_fallback = sock_address;
sock_family = AF_INET6;
sock_address = BIO_ADDRINFO_address(next);
} else if (sock_family == AF_INET6
&& BIO_ADDRINFO_family(next) == AF_INET) {
sock_options &= ~BIO_SOCK_V6_ONLY;
}
}
#endif
asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {
asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);
sock_address = sock_address_fallback;
}
if (asock == INVALID_SOCKET
|| !BIO_listen(asock, sock_address, sock_options)) {
BIO_ADDRINFO_free(res);
ERR_print_errors(bio_err);
if (asock != INVALID_SOCKET)
BIO_closesocket(asock);
goto end;
}
#ifndef OPENSSL_NO_SCTP
if (protocol == IPPROTO_SCTP) {
/*
* For SCTP we have to set various options on the socket prior to
* accepting. This is done automatically by BIO_new_dgram_sctp().
* We don't actually need the created BIO though so we free it again
* immediately.
*/
BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
if (tmpbio == NULL) {
BIO_closesocket(asock);
ERR_print_errors(bio_err);
goto end;
}
BIO_free(tmpbio);
}
#endif
sock_port = BIO_ADDR_rawport(sock_address);
BIO_ADDRINFO_free(res);
res = NULL;
if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {
BIO_closesocket(asock);
ERR_print_errors(bio_err);
goto end;
}
if (accept_sock != NULL)
*accept_sock = asock;
for (;;) {
char sink[64];
struct timeval timeout;
fd_set readfds;
if (type == SOCK_STREAM) {
BIO_ADDR_free(ourpeer);
ourpeer = BIO_ADDR_new();
if (ourpeer == NULL) {
BIO_closesocket(asock);
ERR_print_errors(bio_err);
goto end;
}
do {
sock = BIO_accept_ex(asock, ourpeer, 0);
} while (sock < 0 && BIO_sock_should_retry(sock));
if (sock < 0) {
ERR_print_errors(bio_err);
BIO_closesocket(asock);
break;
}
BIO_set_tcp_ndelay(sock, 1);
i = (*cb)(sock, type, protocol, context);
/*
* If we ended with an alert being sent, but still with data in the
* network buffer to be read, then calling BIO_closesocket() will
* result in a TCP-RST being sent. On some platforms (notably
* Windows) then this will result in the peer immediately abandoning
* the connection including any buffered alert data before it has
* had a chance to be read. Shutting down the sending side first,
* and then closing the socket sends TCP-FIN first followed by
* TCP-RST. This seems to allow the peer to read the alert data.
*/
shutdown(sock, 1); /* SHUT_WR */
/*
* We just said we have nothing else to say, but it doesn't mean
* that the other side has nothing. It's even recommended to
* consume incoming data. [In testing context this ensures that
* alerts are passed on...]
*/
timeout.tv_sec = 0;
timeout.tv_usec = 500000; /* some extreme round-trip */
do {
FD_ZERO(&readfds);
openssl_fdset(sock, &readfds);
} while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
&& readsocket(sock, sink, sizeof(sink)) > 0);
BIO_closesocket(sock);
} else {
i = (*cb)(asock, type, protocol, context);
}
if (naccept != -1)
naccept--;
if (i < 0 || naccept == 0) {
BIO_closesocket(asock);
ret = i;
break;
}
}
end:
# ifdef AF_UNIX
if (family == AF_UNIX)
unlink(host);
# endif
BIO_ADDR_free(ourpeer);
ourpeer = NULL;
return ret;
}
void do_ssl_shutdown(SSL *ssl)
{
int ret;
do {
/* We only do unidirectional shutdown */
ret = SSL_shutdown(ssl);
if (ret < 0) {
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_ASYNC:
case SSL_ERROR_WANT_ASYNC_JOB:
/* We just do busy waiting. Nothing clever */
continue;
}
ret = 0;
}
} while (ret < 0);
}
#endif /* OPENSSL_NO_SOCK */
| 16,536 | 32.408081 | 81 |
c
|
openssl
|
openssl-master/apps/lib/tlssrp_depr.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is to enable backwards compatibility for the SRP features of
* s_client, s_server and ciphers. All of those features are deprecated and will
* eventually disappear. In the meantime, to continue to support them, we
* need to access deprecated SRP APIs.
*/
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/bn.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/srp.h>
#include "apps_ui.h"
#include "apps.h"
#include "s_apps.h"
static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
{
BN_CTX *bn_ctx = BN_CTX_new();
BIGNUM *p = BN_new();
BIGNUM *r = BN_new();
int ret =
g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
BN_check_prime(N, bn_ctx, NULL) == 1 &&
p != NULL && BN_rshift1(p, N) &&
/* p = (N-1)/2 */
BN_check_prime(p, bn_ctx, NULL) == 1 &&
r != NULL &&
/* verify g^((N-1)/2) == -1 (mod N) */
BN_mod_exp(r, g, p, N, bn_ctx) &&
BN_add_word(r, 1) && BN_cmp(r, N) == 0;
BN_free(r);
BN_free(p);
BN_CTX_free(bn_ctx);
return ret;
}
/*-
* This callback is used here for two purposes:
* - extended debugging
* - making some primality tests for unknown groups
* The callback is only called for a non default group.
*
* An application does not need the call back at all if
* only the standard groups are used. In real life situations,
* client and server already share well known groups,
* thus there is no need to verify them.
* Furthermore, in case that a server actually proposes a group that
* is not one of those defined in RFC 5054, it is more appropriate
* to add the group to a static list and then compare since
* primality tests are rather cpu consuming.
*/
static int ssl_srp_verify_param_cb(SSL *s, void *arg)
{
SRP_ARG *srp_arg = (SRP_ARG *)arg;
BIGNUM *N = NULL, *g = NULL;
if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
return 0;
if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
BIO_printf(bio_err, "SRP parameters:\n");
BIO_printf(bio_err, "\tN=");
BN_print(bio_err, N);
BIO_printf(bio_err, "\n\tg=");
BN_print(bio_err, g);
BIO_printf(bio_err, "\n");
}
if (SRP_check_known_gN_param(g, N))
return 1;
if (srp_arg->amp == 1) {
if (srp_arg->debug)
BIO_printf(bio_err,
"SRP param N and g are not known params, going to check deeper.\n");
/*
* The srp_moregroups is a real debugging feature. Implementors
* should rather add the value to the known ones. The minimal size
* has already been tested.
*/
if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
return 1;
}
BIO_printf(bio_err, "SRP param N and g rejected.\n");
return 0;
}
#define PWD_STRLEN 1024
static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
{
SRP_ARG *srp_arg = (SRP_ARG *)arg;
char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
PW_CB_DATA cb_tmp;
int l;
cb_tmp.password = (char *)srp_arg->srppassin;
cb_tmp.prompt_info = "SRP user";
if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
BIO_printf(bio_err, "Can't read Password\n");
OPENSSL_free(pass);
return NULL;
}
*(pass + l) = '\0';
return pass;
}
int set_up_srp_arg(SSL_CTX *ctx, SRP_ARG *srp_arg, int srp_lateuser, int c_msg,
int c_debug)
{
if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg->srplogin)) {
BIO_printf(bio_err, "Unable to set SRP username\n");
return 0;
}
srp_arg->msg = c_msg;
srp_arg->debug = c_debug;
SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
SSL_CTX_set_srp_strength(ctx, srp_arg->strength);
if (c_msg || c_debug || srp_arg->amp == 0)
SSL_CTX_set_srp_verify_param_callback(ctx, ssl_srp_verify_param_cb);
return 1;
}
static char *dummy_srp(SSL *ssl, void *arg)
{
return "";
}
void set_up_dummy_srp(SSL_CTX *ctx)
{
SSL_CTX_set_srp_client_pwd_callback(ctx, dummy_srp);
}
/*
* This callback pretends to require some asynchronous logic in order to
* obtain a verifier. When the callback is called for a new connection we
* return with a negative value. This will provoke the accept etc to return
* with an LOOKUP_X509. The main logic of the reinvokes the suspended call
* (which would normally occur after a worker has finished) and we set the
* user parameters.
*/
static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
{
srpsrvparm *p = (srpsrvparm *) arg;
int ret = SSL3_AL_FATAL;
if (p->login == NULL && p->user == NULL) {
p->login = SSL_get_srp_username(s);
BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
return -1;
}
if (p->user == NULL) {
BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
goto err;
}
if (SSL_set_srp_server_param
(s, p->user->N, p->user->g, p->user->s, p->user->v,
p->user->info) < 0) {
*ad = SSL_AD_INTERNAL_ERROR;
goto err;
}
BIO_printf(bio_err,
"SRP parameters set: username = \"%s\" info=\"%s\" \n",
p->login, p->user->info);
ret = SSL_ERROR_NONE;
err:
SRP_user_pwd_free(p->user);
p->user = NULL;
p->login = NULL;
return ret;
}
int set_up_srp_verifier_file(SSL_CTX *ctx, srpsrvparm *srp_callback_parm,
char *srpuserseed, char *srp_verifier_file)
{
int ret;
srp_callback_parm->vb = SRP_VBASE_new(srpuserseed);
srp_callback_parm->user = NULL;
srp_callback_parm->login = NULL;
if (srp_callback_parm->vb == NULL) {
BIO_printf(bio_err, "Failed to initialize SRP verifier file \n");
return 0;
}
if ((ret =
SRP_VBASE_init(srp_callback_parm->vb,
srp_verifier_file)) != SRP_NO_ERROR) {
BIO_printf(bio_err,
"Cannot initialize SRP verifier file \"%s\":ret=%d\n",
srp_verifier_file, ret);
return 0;
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);
SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
return 1;
}
void lookup_srp_user(srpsrvparm *srp_callback_parm, BIO *bio_s_out)
{
SRP_user_pwd_free(srp_callback_parm->user);
srp_callback_parm->user = SRP_VBASE_get1_by_user(srp_callback_parm->vb,
srp_callback_parm->login);
if (srp_callback_parm->user != NULL)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm->user->info);
else
BIO_printf(bio_s_out, "LOOKUP not successful\n");
}
| 7,325 | 30.577586 | 91 |
c
|
openssl
|
openssl-master/apps/lib/vms_decc_argv.c
|
/*
* Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <openssl/crypto.h>
#include "platform.h" /* for copy_argv() */
char **newargv = NULL;
static void cleanup_argv(void)
{
OPENSSL_free(newargv);
newargv = NULL;
}
char **copy_argv(int *argc, char *argv[])
{
/*-
* The note below is for historical purpose. On VMS now we always
* copy argv "safely."
*
* 2011-03-22 SMS.
* If we have 32-bit pointers everywhere, then we're safe, and
* we bypass this mess, as on non-VMS systems.
* Problem 1: Compaq/HP C before V7.3 always used 32-bit
* pointers for argv[].
* Fix 1: For a 32-bit argv[], when we're using 64-bit pointers
* everywhere else, we always allocate and use a 64-bit
* duplicate of argv[].
* Problem 2: Compaq/HP C V7.3 (Alpha, IA64) before ECO1 failed
* to NULL-terminate a 64-bit argv[]. (As this was written, the
* compiler ECO was available only on IA64.)
* Fix 2: Unless advised not to (VMS_TRUST_ARGV), we test a
* 64-bit argv[argc] for NULL, and, if necessary, use a
* (properly) NULL-terminated (64-bit) duplicate of argv[].
* The same code is used in either case to duplicate argv[].
* Some of these decisions could be handled in preprocessing,
* but the code tends to get even uglier, and the penalty for
* deciding at compile- or run-time is tiny.
*/
int i, count = *argc;
char **p = newargv;
cleanup_argv();
/*
* We purposefully use OPENSSL_malloc() rather than app_malloc() here,
* to avoid symbol name clashes in test programs that would otherwise
* get them when linking with all of libapps.a.
* See comment in test/build.info.
*/
newargv = OPENSSL_malloc(sizeof(*newargv) * (count + 1));
if (newargv == NULL)
return NULL;
/* Register automatic cleanup on first use */
if (p == NULL)
OPENSSL_atexit(cleanup_argv);
for (i = 0; i < count; i++)
newargv[i] = argv[i];
newargv[i] = NULL;
*argc = i;
return newargv;
}
| 2,386 | 31.69863 | 74 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.